121 points · by signa11 · 3y ago · 114 comments
1) Most code, i.e. at least 80% of the code in a codebase, will never be a performance hotspot and does not need specific optimizations (i.e. as long as the code does not do stupidly inefficient things, it's probably good enough).
2) Even in performance hotspot codepath, you should not write unnecessarily hard to read code unless it is strictly necessary to achieve required performance.
In both cases, the key point is to benchmark and profile to find the specific places where the ugly hacks need to be introduced, and do not introduce more than is strictly necessary to get the job done.
> 1) Most code, i.e. at least 80% of the code in a codebase, will never be a performance hotspot and does not need specific optimizations (i.e. as long as the code does not do stupidly inefficient things, it's probably good enough).
The hard part is knowing what "stupidly inefficient things" are. If you never do excessive optimization, its easy to drift towards less efficient over time because your baseline for what performance is possible slows down. Knowing how to do performance optimization that is not worth it and knowing what the best level of efficiency to shoot for is the mark of a good engineer.
To do that the team needs experience with performance, and most of internet programmer culture is just to lecture people about how programmers are cheaper than hardware if anyone asks or talks about performance. So many people don't get that experience.
This is very true. The misuse of the "premature optimization" mantra and the thought that valuable programmer time should never be spent on performance have done a disservice to a generation or two of developers. To the point that so many developers don't even believe performance has any significance and the cloud just magically makes it fast.
Spending a week optimizing some function to shave off a few seconds may be totally worth it, just depends how often it runs. If it is a code path being used by millions of people, it can quickly become very valuable.
Cost is another factor. Sure you might be able to effortlessly spin up dozens or hundreds more instances on demand to handle the load because the code is so slow one instance can barely handle a few dozen requests per second, but you're paying for that. Make an instance capable of handling a few thousand rps and suddenly you've save very real money.
And battery life on all portable devices also benefits from more efficient CPU usage.
My experience with JVM over the last few years says otherwise. Most teams I have come across try too hard to achieve "performance" where very simple idiomatic code would have sufficed. Idiomatic code improves in performance every release. Instead they picked up some dogmas based on JVMs of the past and their "peformance culture" is a farce.
But this is an absolute truth, isn't it?
I mean, what's more important to your business: avoid the need to launch an EC2 instance, or implement that user flow in one day instead of one week? Do you care if it takes 50ms to show your dialog box instead of 40ms? Do you really care if you pass all your objects by value, with a few deep copies, instead of passing everything by reference?
The truth of the matter is that in general all performance bottlenecks are caused by software architecture and algorithms, not "clean code" implementations.
Did you mean the reverse of this, I assume?
This is a problem that absolutely plagues our field. If your project isn't some wrapper around some incredibly complicated math or handling files well into the GB range, there's no excuse for a desktop application to take noticeable time to do anything. Yet here we are, with it taking about a half second just to open the search bar on windows. What is it doing? Why does it take so long? Who knows?
There are things that are quite obvious non-critical in terms of performance.
One time I had a junior engineer insisting in a PR that we should use a few low-level performance tricks in a code because it was fast, and the code was to open a dialog box.
Also, in general performance bottlenecks are caused by architectural and algorithmic choices, not readability choices. If we're in a domain where, say, inheritance is an unacceptable performance bottleneck and we need to unroll loops and we can't extract functions because the cost of pushing the call stack is prohibitive... We are in an extremely performance-sensitive part of the code.
But most of the time we're far from any of that.
It's not really true that 80% of the code doesn't matter. 80% of the code might not matter the way it is currently designed, but that doesn't mean a different design isn't dramatically better. Benchmarking and profiling doesn't help with that. Real expertise is required and that is developed over time by people who care about improving performance and make it a priority.
You know, when money is flowing in, you have to hire some good people, let them spend time on fixing hotspots and in some rare occasions, rearchitecture a part or maybe two. Probably won’t pay off, but if you are growing fast enough, it will pay 100x.
Also you’re decreasing all future development speed with all this unreadable shit everywhere, so beware of optimizing unnecessary stuff.
High performance doesn't mean unreadable. Microoptimizations can make code less readable, true, but they also give you the least amount of speedup (in the best case you can get several times speedup if you found some hotspot that can be vectorized, but that's pretty rare). You can get huge performance improvements by optimizing networking and system calls and doing that doesn't make much of an impact on readability.
And UI is a bad example IMHO. UI with a high response time which is uncomfortable (or even frustrating) to use is probably the result of thinking that UI performance doesn't matter.
I've learned that benchmarking and profiling is the _only_ way to write performant code.
I've seen in code review a number of examples of a very fancy algorithm being broken out, and asked, "You realize N is bounded to be at most 100 here?". Or, "you realize the thread overhead here for parallel processing is two magnitudes slower than serial data access on one thread?"
Humans are bad at intuitively understanding where the slow parts of code are. I've seen processing be improved to the point of impossible to grok, shaving 10ms of a processing piece that is 50ms long, only to then spend time blocking waiting for network transfers that require 10s.
I'm of the opinion the biggest performance improvements are usually in design and architecture. What if there were a design that avoided the need to do any network IO? In that case the 10s + 50ms would be a 50ms process, rather than a hard to grok "optimized" 10s + 40ms process. Simple code leads to simpler design, which is easier to reason about and spot the places where things like "this entire network round trip can be cut out", or "we are loading this data multiple times throughout this process, we can load it once", or "we are loading this data and then spending a lot of time querying "n+1", instead if we stored the data in this format with some pre-processing we'll avoid the "n+1" query."
To further rant, the emphasis of algorithms in coding interviews, people enjoying algorithms more than cleaning up crufty architecture - that is the root of a lot of bad software rather. In sum, it's almost always the design that is slow, rarely it's the algorithm. The profiling is key as it let's you know where things are actually slow. (Recently a colleague was trying to optimize a tight loop that processed 1.5M rows. To "optimize" memory usage, they converted all variables to static to 'save' memory and avoid GC pauses. This in effect did _nothing_, the compiler instead was going to inline all the variables anyways and the resulting bytecode was not going to have any extra variables in at all. Converting local variables to static actually made the memory usage just slightly worse. So, this 'optimization' did nothing but make the code worse. A quick benchmark would have shown that optimization having no effect (to really optimize memory usage, we updated the design to stream results to a file rather than keep everything in memory for a final dump to file at the very end). Another example, I once helped a team do performance work for a DB that they spent a year tuning. They did not keep track of any performance benchmarks, what changes did what improvement; and after a year had nothing to show except for a DB that would crash after a few minutes. Taking that over, starting everything over from scratch, benchmarking everything, the project was done a month later and was stupid fast.)
it's important to make sure your code base isn't doing anything dumb, like O(n^2) iterations, or 1000 sequential RPCs instead of 1 batch RPC, or etc -- this is i guess your point about architecture
but assuming that bar is cleared, performance optimizations should only be accepted when accompanied by benchmarks/profiles that demonstrate their usefulness at the whole system level
In practice, most of the industry has been writing ridiculously inefficient code for decades, and I wish more people would pay attention to that 20%, or the 3% that Knuth described.
Or better yet, I wish some groups don't irreversible sacrifice performance with frameworks and architectures that are impossible to optimize, no matter how the code is written.
I agree with both of you - there's no reason why software should be as inefficient as it is, and there's also no reason why code should be as unreadable as it is, and those goals aren't mutually exclusive.
Except that it is, and it tends to be development speed.
For example, real world React apps tend to suffer a lot from performance issues, specially when compared with vanilla html+javascript or even the old but true server-side rendered HTML, but it also makes it trivial to implement and rewrite complex UIs that UX designers love to put together. Would it make sense to argue for performance options which lead to productivity hits?
That's true, however, I've seen enough code where the author used this argument as a justification to do stupidly inefficient things, such as building monstrous mountains of abstraction layers (or re-scan the entire codebase at runtime because why not? [1]) all covered by the "premature optimization is the root of all evil" mantra.
You can absolutely write code that is both opaque and inefficient.
[1] https://docs.spring.io/spring-framework/docs/3.0.0.M4/spring...
Yes, and no. That's what makes it hard to write high performance systems, you really need people with solid experience in designing for performance.
Sure, always go for the low hanging fruit which are the hotspots identified by profiling and improve those.
But what often happens after that is that all the code is slow everywhere! So there are no big hotspots, profiling shows nothing egregious. Teams without high performance systems experience might conclude the code is about as good as it can get given the absence of hotspots. Seen this happen often. But there might be 10x or 100x improvements remaining.
On the other hand, we should talk about "doing stupid things", or having a bad design/architecture. For example, if you architect your application such that each web request is serviced by 20 micro-services, and those micro-services make 20 requests of their own...no matter how fast your code is, the application will be slow.
In latency sensitive code, _all_ code needs to be optimized. It doesn't matter if your slow function is only called once - it adds N microseconds of latency when it doesn't need to.
And sure, once that's done, you can keep going to picoseconds, but there's only a limited number of application areas where that makes economic sense.
It's also important to consider the entire system: you can optimize your code to the picosecond level, occupying the time of expensive engineers for months, but perhaps that $500k is better deployed on a PCIe5 bus, or a better Ethernet card, or a kernel-bypass stack, or even shorter network cables (every 300mm is a nanosecond, after all).
unless your slow function materially impacts your performance metrics in a way that you can reproducibly demonstrate, it's a mistake to optimize that code to shave off a few microseconds
Difficulty in that last is that the best practice for how to maintain code changes as you get older on the project. This is easy to see in code that is a bit of a mungled mess. But it is also visible on code that it is a beautiful stalled out mess of needing too much to get small contributions in.
Well, ironically, the site itself is down (so the code must be beautiful?) but assuming I understand the content from the title, another thing that most of these "code quality doesn't matter" types overlook is that software changes over time, quite a bit. That's why it's called "soft"ware, it's supposed to be soft. Readable is changeable. If all the mattered were performance, we'd engrave the code path onto a circuit board.
I really wish people would stop pushing back on people who are interested or curious about how to make code perform better. Of course you don't want people scattering weird SIMD intrinsics all over mundane parts of your web backend in an unhinged attempt to shave microseconds off a response. But in my career I've never really seen people do this anyway.
What you do want though is programmers who have spent some time understanding how to structure code to perform well on modern hardware. Because often times that structure is NOT a mess, it may even be easier to work with that the usual idioms in your industry or language. Grouping data into adjacent chunks with arrays or array backed data structures has more benefits than just leveraging the L1 cache. It is sometimes also convenient.
Given that it was from a consultancy advertising its optimization services, the irony of it going down is still pretty high, though.
That was kind of the point. There is no empirical evidence showing that the "clean code" way of programming is any better in terms of cognitive load, but there is empirical evidence that it makes your program perform very poorly.
The video also did not aim to produce "the most performance code possible", which would certainly become a tangled web of arcane bit tricks and CPU minutiae. It was demonstrating what reasonable performance might look like, if you wrote simple code that the compiler can do a good job at optimizing.
In addition, he demonstrated very clearly that doing it the "clean" way was significantly worse in terms of being able to see that the optimizations he did were even possible, so, that observation argues that the "clean" principals not only make your code slow as shit, but ALSO harder to reason about.
I program in a similar style to Casey all day, every day, and I typically have no trouble going to code I wrote years ago and figuring out what's going on.
If that doesn't convince you that it's an unjustified and useless way of thinking about programming, I'm not sure what would.
My first reaction is that I like this idea, but maybe I’m biased because I feel I’d “pass the test” myself (and thus have one additional small way to differentiate myself from pure Leetcoders :)
In most of the environments I’ve worked (except maybe the games companies) I feel this would not have been widely considered an acceptable thing to ask in a generalist interview.
Or perhaps it was actually an incredibly good example, despite itself: a great illustration of precisely why jumping to micro-optimization isn't always the right solution.
That is not always the case, but this is one of the times when it is.
So they're almost certainly wrong...
I think actual horrible code is more something that uses global mutable state, has logic spread over half a dozen units or does have weird roundabout implementations - however not because of a particular reason but because of unclear goals, big-ball-of-mud architecture, evolving codebase etc.
[1] https://tvtropes.org/pmwiki/pmwiki.php/Main/HollywoodHomely
I picked this practice up from an older engineer who would set
SLOW = false
at the top of the file and then wrap old code in a if (SLOW) { … }
block for the compiler to do dead code elimination on. (I found linters and compilers complained less about commented-out code, but he preferred his way so it would always have syntax highlighting.) static bool set_t_contains_fast(set_t x, uint64_t e);
static bool set_t_contains_simple(set_t x, uint64_t e);
bool set_t_contains(set_t x, uint64_t e)
{
bool f = set_t_contains_fast(x, e);
assert(set_t_contains_simple(x, e) == f);
return f;
}
sometimes with a CONTRACTS macro controlling it instead of an assert.I had a memorable experience of that, actually - for a long time we had a Trello card titled “faster to operate on the bits instead”, and the team looked at that card fondly during development. After we started getting traction, it was finally time to optimize! We conscientiously wrote tests to ensure correctness, and then began an incredibly enjoyable informal hackathon. We blazed through every step, replacing the logic piece by piece with bit operations. This step was 2x faster, that step was 5x faster, and so on. A few steps were slower, which was a bit weird, but we were having so much fun shouting out our gains to each other across the room, racing to improve. By the afternoon we had optimized each step and gotten an order of magnitude improvement.
“Great stuff, team.”
“I thought it would have been faster.”
“Yeah, same.”
We did some evening profiling and noticed a lot of time being spent in a dozen or so functions with names like “toRepr”, “reconstitute”, stuff like that. Actually it was like most of the time - what!? And then we saw, at each step we converted to raw bits, performed the equivalent logic with fast bit operations, then converted back to the representation for handoff to the next step. Wait, why we are converting to and from bits like thirty times each run? That can’t be right. Realization strikes - right before most handoffs there was a commented-out line that ran out tests on the representation to ensure it was still correct.
Someone pointed out we wrote that test before we had done any investigation of performance (I remember it almost word for word actually, “When we wrote the test, all we knew was it would be faster in bits, but not how. And the test doesn’t even look at bits!”). So we ripped out all the conversions and stayed in bits from step to step. Without changing the bit logic it was now almost three orders of magnitude performance gain, basically running in milliseconds instead of seconds. Two OOM that we had earned, but left on the table!
Tests introduced arbitrary checkpoints and imposed irrelevant constraints on the problem, without us noticing until afterwards. We caught the problem pretty easily that time, but I do wonder how many other times we (or others) didn’t because it wasn’t as obvious. The service that accepted the output maybe should have been accepting raw bits instead of the representation. The service that gave us the input definitely should have been staying in the bits.
So, do test your optimizations for correctness, but be really careful. Tests can easily and subtly constrain your optimization space in major and arbitrary ways!
The idea that test design can actually constrain your solutions if your tests are too opinionated about implementation is fascinating.
Seems like maybe optimization needs to be a loop of "we optimize the code, then we optimize the tests"
Something to that effect.
On that topic, probably one of the top-3 features from Clojure I miss in other languages, is having the option of making comments being a part of the language itself so everything that works on the code (linters, evaluation, syntax highlighting, etc) works in the comment as well. The `comment` macro really is a godsend in disguise as it's awfully simple implementation-wise. Its cousin `#_` is also a great tool. See https://clojuredocs.org/clojure.core/comment for more examples
maybe the code behind his blog is too clean!
In cases like ECS (in gaming) or virtual DOM (in web), the "horrible" architecture comes out the other side and becomes almost clean again.
I work in-house for a non-tech related company. I'm often the sole developer, sometimes I have help. I'm also the defacto DBA and systems administrator for the machines the software runs on. As the defacto DBA, I'm also roped into data analysis as well.
There are also certain events that are non-compromisable. These events take place whether we are ready or not. Having nothing is not really an option. That means shelving the project until next year. Because the next event must be prepared for.
So, at the end of the day, "done is best". If I have the time, I can go back and refactor everything into something better. But often, there's "the next thing".
I would first look in the 5 book TAOCP for an algorithm recipe.
Then, I would look to other FOSS implementations that solved a particular problem before.
If you need to write something totally new, consider first why you must put dense engineering effort into something that may already exist. Do you really need to be solving this problem?
I wouldn't call the Python dict implementation amateur.
Furthermore, the only way to arrive at optimal implementations for various platforms is to benchmark them. You won't get that just guessing or labeling things you know nothing about "amateur".
clean, adjective
1. Free from dirt, stain, or impurities; unsoiled.
2. Free from foreign matter or pollution; unadulterated.
3. Not infected.
4. Honest or fair, or showing that you have not done anything illegal
Clean isn't a word that can be used to describe software. It just doesn't have any relevance to an observable, objective quality of software. There is no definition of what 'clean' code is; you can't show me code and say objectively "this is not clean", because there's no real definition of "clean code". It's a loan word, seemingly to indicate a lack of desirability or quality. And it also implies things that don't have anything to do with software. But there really is no concrete example or evidence of what clean software is. So it's nonsense.We talk about a computer "science". But in reality it's not a science, it's a cargo cult. We use imprecise language with no concrete definition of what we're actually saying and doing. And we wonder why the end result is so poor.
Most creative trades share a definition of clean that expands on #2, where 'foreign matter' includes items, not detritus. If you leave a toothbrush on your desk the desk is not clean, even if the toothbrush is still new in the wrapper. It can also mean 'cleared and ready to begin a new task', which is a step that would precede any mis-en-place work one might engage in before properly starting the task.
Clean means something beyond that in software. It's fairly well agreed upon. It's not in the dictionary. That doesn't invalidate it.
Then could you share that agreed-upon definition with me? And also, exactly how much is "fairly well" agreed upon? 60%? So would 2/5 of people disagree when you call some code unclean? Are there classes where they teach kids in school how to identify unclean code? Are there instructions on how to clean it up?
And most importantly, is there any kind of scientific research that shows the effects of unclean code? Or are humans just overly concerned with appearances, and make up their own rituals and reasons for whatever becomes habitual?
This is a thing to think about in itself. One problem here is languages that have semantics hostile to significant data layout transformations. Practically to get there the language design and the data-optimizing compiler would have to co-evolve I think.
If you have a high performance requirement you should extract that code into its own “space” and not try to make the existing system shitty.
Use API contracts between systems and don’t muddy up existing systems.
With tools like ChatGPT - we can have both readability AND performance, right??
Or am I missing something?
While I'll cop to being more skeptical than the average HN denizen about ChatGPT, this isn't actually cynicism about ChatGPT, but about human cognition. If we do have something that produced large swathes of mostly correct code, it won't be long before the humans using it aren't even checking it anymore. Same reason that cars can do a little bit of assisting, and if they could do 100% of the driving that might be safe, but 98% of the driving is not a very good idea at all.
In 20 years, someone will ask CodeGPT 8.3 to explain what some code does, and it'll give a perfectly understandable explanation back, except the human still won't understand it because the human doesn't actually understand how computers work anymore. They'll think they understand it, though.
The problem is that they've chosen a micro benchmark for this argument. The toy-est of toy problems. Yes, you have to make tradeoffs in these cases, but toy problems aren't really a good communication medium. If you want to process a thousand records of data in a decent amount of time, there are lots of strategies that move you toward achieving both.
I've not seen anyone seriously attempting to benchmark chatgpt output, without heavily cherry picking it first.