281 points · by benaadams · 8y ago · 162 comments
Totally true, and I have observed it IRL on large, old projects whose architecture was hostile to performance. And these products were doing computationally intense stuff.
> Performance is everyone’s responsibility and it needs to be part of the process along the way.
Yes.
Everyone repeats "only optimize after profiling". It's true: if your program is running too slowly, you should always profile. But that rule only applies when your code is already slow. It doesn't actually say anything about the rest of the development process.
Developers should have a solid grasp of computer hardware, compilers, interpreters, operating systems, and architecture of high performance software. Obliviousness to these is the source of performance-hostile program designs. If you know these things, you will write better performing code without consciously thinking about it.
If this knowledge is weighed more heavily in the software dev community, people will put in the effort to learn it. It's not that complicated. If the average dev replaced half of their effort learning languages, libraries, and design patterns with effort learning these fundamentals, the field would be in a much better place.
If developers learn 2 basic things:
1. How SQL queries work
2. Network latency exists. Moving stuff between your database and your server can get expensive.
You'll solve _most_ of the issues that I've seen in my career to this point. There are a few big ones that came from abusing API's too, but it's really the same root issue:
You're either thinking about how much information is being moved around or you're not.
Also, for parallel stuff: locks tend to be bottlenecks. Writing parallel code is tricky overall. Stick to libraries that provide high level lockless data structures like mpsc queues if possible.
Not to put too fine a point on it, but I think you meant how often information is being moved around. That's the scenario where latency has a disproportionate effect on performance.
(Bandwidth is usually not a problem these days unless you're doing something at the very high end.)
4. When [not] to use the network
A lot of the performance wins I have been able to pull off (1000x) were from removing unnecessary distribution and unnecessary databases.
Eventually you have an unending field of nearly identically tall poles, everyone claims victory (we’ve done all we can!). But your sales team is still mad because your product is several times slower than the competing products.
What do we call this? Picket fence? Blanket of doom? Death shroud? Forest for the trees? Stupidity?
The old advice is to optimize intelligently, based on actual data, not preconceived notions. If your program isn't correct, then it's hard to have valid performance data, so optimizing before your program is correct is problematic. Kent Beck has an anecdote about being called in to optimize the Chrysler C3 payroll system. He arrives, then asks if there is a valid input/output dataset. The Chrysler people tell him that the system isn't producing valid outputs yet. His reply: "Well in that case, I can make it Real Fast!"
(As it turns out, a lot of the performance problems came down to naive string concatenation!...O(n^2)...yadda yadda.)
You can absolutely aim for both correctness and performance in your design. In fact performance is (can be) part of correctness, if it doesn't perform to spec then it's most likely not useful. If you don't care about performance, fine, don't design for it and don't optimize.
Your starting point for optimization has to be a solid design with specific performance goals in mind. If you have a solid design maybe you won't need to do any optimization, if you do it's going to be optimizing on top of the design.
I rub elbows with landscapers in one of my hobbies and the general consensus seems to be that leaving fruit or leaves under your tree as pathogen vectors is a bad plan. That it’s better to hot compost everything you can’t grab before it hits the ground. We have orchard ladders (the ones with the flared base) and telescoping handheld pickers and dwarf varieties (trees with better modularity?) that keep most of the fruit within picking distance.
Also leaving ripe fruit in the trees just means the wildlife or storms have a chance to get it before you can.
I don’t have any mature fruit trees now but my plan is similar to my friend who has five apple trees. Harvest as much as I can process at a go (she makes cider). And then whatever the animals don’t get after that is a bonus.
I think you misunderstood the instructions and anecdotes that you were given about how and when to optimize. Alternatively, your definition of "old" in "old advice" is a very short time in the past.
I spent a big chunk of my early career doing performance analysis work in a language stereotyped as being slow. My thesis was that it was down to developer skill and not the language. By the time someone spoke Knuth's aphorism at me it was people who were standing between me and the strategic goals of the company. Using it as a shield to get out of doing the hard work to match a competitor or customer expectations.
As I quickly discovered, there are a whole set of performance optimizations that also improve readability, and that got around the friction with the foot dragging Knuth quoters. There's a host of other things never show up in the literature. It's a shame, really.
I don't know a fruit grower. Can you tell me?
So either you pick all of the ripe fruit, or you pick everything. By shaking the tree and catching everything that falls out.
I've never heard that "old advice" and I've been doing this for 20 years. If you are referring to the quote about "premature optimization" you are misinterpreting it badly, or had it explained to you badly.
The gamedev people care, because in games, you have hard performance constraints (60+ FPS) and try to cram in as much stuff as possible, so you always have resource use on your mind. Embedded people probably care too (I hear they do, but don't have much personal experience there). Most other branches of this industry couldn't give two fucks about it, as evidenced by software we use daily on the web and our phones. There is no market pressure to optimize, so people can get away with releasing slow and resource-intensive software. General population has been conditioned to think that if an app or webpage works slowly, they need to buy a faster computer/phone. They should instead be concluding that the app is most likely garbage.
(Note that optimization is not just about CPU cycles. Other resources are important. These days, it's more likely you'd exhaust RAM and make everything slow by forcing system to swap too much than it is that your application will use 100% CPU.)
I can count on my fingers the number of times I've heard Knuth quoted properly (and always to jr developers). And I've been at this for 25.
What about the fruit rotting on the ground? That's one of our favorite analogies.
Except for unusually throwaway or easy to make fast enough projects, software should also be profiled when it runs fast, before there are performance problems.
Profiling the application from the beginning ensures readiness when profiling is urgently needed, provides a reference point for what good performance looks like, and most importantly allows easy and early detection of performance mistakes and regressions, which can be troublesome and expensive in the long run, growing into "deep systemic issues" even if they are harmless when they first appear.
It is virtually never the case that profiling reveals a uniformly slow mess of code, and in many cases this doesn’t even make sense as a possibility because you write modular performance tests and profiling tools the same as you write modular unit tests. You would never fire up the profiler and just naively profile a whole backend service all at once, apart from maybe getting extremely coarse latency statistics that only matter in terms of what stakeholder constraints you have to meet. For analyzing cases when you’re not just gathering whole-service stats for someone else, you’d always profile in a more granular, experiment-driven way.
> “Developers should have a solid grasp of computer hardware, compilers, interpreters, operating systems, and architecture of high performance software. Obliviousness to these is the source of performance-hostile program designs. If you know these things, you will write better performing code without consciously thinking about it.”
While it’s good to know more about more things generally, I think the specific claim that any of this will help you design better code in the first place is totally and emphatically wrong.
Instead it leads you down wrong tracks of wasted effort where someone’s “experience and intuition” about necessary optimizations or necessary architectural trade-offs ends up being irrelevant to the eventual end goal, the changing requirements from the sales team, etc. etc.
This happens so frequently and clashes so miserably with a basic YAGNI pragmatism that it really is a good heuristic to just say that early focus on optimization characteristics is always premature.
In the most optimization-critical applications I’ve worked on, getting primitive and poorly performing prototypes up and running for stakeholders has always been the most critical part to completing the project within the necessary performance constraints. Treating it like an iterative, empirical problem to solve with profiling is absolutely a sacred virtue for pragmatically solving the problem, and carries far, far less risk than precommitting to choices made on the speculative basis of performance characteristics borne out of someone else’s “experience” with performance-intensive concepts or techniques. Such experience really only matters later on, long after you’ve gathered evidence from profiling.
> “Once you have 100,000 lines of code that all operate on that linked list, you are stuck with it.”
No, I think this really is not true, and as long as the new “performant” redesigned linked list that you want to swap in can offer the same API, then this is a relatively easy refactoring problem. I’ve actually worked on problems like this where some deeply embedded and pivotal piece of code needs to be refactored. This is a known entity kind of problem. Unpleasant, sure, but very straightforward.
You seem to discount the reverse version of this problem which I’ve found to be far more common and more nasty to refactor. In the reverse problem, instead of being “stuck” with a certain linked list, you end up being stuck with some mangled and indecipherable set of “critical sections” of code where someone does some unholy low-level performance optimization, and nobody is allowed to change it. You end up architecting huge chunks of the system around the required use of a particular data flow or a particular compiled extension module with a certain extra hacked data structure or something, and this stuff accumulates like kruft over time and gets deeply wedded into makefiles, macros, and deployment scripts, etc., all in the name of optimization.
Later on, when requirements change, or when the overall system faces new circumstances that might allow for trading away some performance in favor of a more optimized architecture or the use of a new third party tool or something, you just can’t, because the whole thing is a house of cards predicated on deep-seated assumptions about these kludged-together performance hacks. This is usually the death knell of that program and the point at which people reluctantly start looking into just rewriting it without allowing any overcommitment to optimization.
(One example where this was really terrible was some in-house optimizations for sparse matrices for text processing. Virtually every time someone wanted to extend those data structures and helper functions to match new features of comparable third-party tools, they would hit insane issues with unexpected performance problems, all boiling down to a chronic over-reliance on internal optimizations. It made the whole thing extremely inflexible. Finally, when the team decided to actually just route all our processing through the third party library anyway, it was then a huge chore to figure out what hacks could be stripped away and which ones were still needed. That particular lack of modularity truly was caused specifically by a suboptimal overcommitment to performance optimization.)
“Overcommitting” is usually a bad thing in software, whether it’s overcommitting to prioritize performance or overcommitting to prioritize convenience.
The difference is that trying to optimize performance ahead of time often leads to wasted effort, fast running things that don’t solve a problem anyone cares about anymore or lack that critical new feature which totally breaks the performance constraints.
Optimizing to make it easy to adapt, hack these things in, have a very extensible and malleable implementation is almost always the better bet because the business people will be happy you can accomodate rapid changes, and more able to negotiate compromises or delayed delivery dates if the flexibility runs into a performance problem that truly must be solved.
Avoiding abstraction is another form of premature optimisation.
Once a design such as a linked-list of polymorphic classes being iterated on in a loop is established, it is hard to refactor.
Those with performance experience would understand that this design will have caching, branch prediction and similar issues.
However, I totally agree with you that the overall implementation should be driven by iterative coding and profiling.
BUT when it is time to choose memory layouts, data models, etc - planning in advance with an eye to performance is very valuable.
I think you're right in that attempting to write code that specifically matches all these things is likely to prematurely optimize. I develop on Linux on an Intel consumer desktop processor, and OS X on an Intel consumer laptop processor, and I deploy to a containerized instance running on a virtualized Intel processor running on an Intel server processor. This lets me get to market quite fast. And I should be trying to figure out the wide instructions on the Intel server and if they're a good idea? I didn't even know about pcmp{e,i}str{i,m} until a couple of years ago and I have used it precisely zero times.
As it stands, 400k rps and logging every request, for an ad syncing platform, and it's not breaking the bank. Spending time to learn the intricacies of the JVM is not likely to have yielded improvements.
'The death of optimizing compilers'
https://cr.yp.to/talks/2015.04.16/slides-djb-20150416-a4.pdf
Key quote:
"Except, uh, a lot of people have applications whose profiles are mostly flat, because they’ve spent a lot of time optimizing them.”
— This view is obsolete.
Flat profiles are dying. Already dead for most programs. Larger and larger fraction of code runs freezingly cold, while hot spots run hotter. Underlying phenomena: Optimization tends to converge. Data volume tends to diverge.
In that case, it’s absolutely a best practice to start out with that 10x-too-slow-but-easy-to-implement-for-stakeholders version, and only harden or tighten your homemade computer vision code or use of opencv or some neural network tool after profiling.
> “Where it does get interesting is situations like games / garbage collectors where you want to minimise latency. On such problems you usually cant bolt on performance after the fact.”
No, that’s exactly the sort of case I’m talking about. It’s not only possibly to refactor for performance after the fact, but dramatically easier to do so, less risky in terms of optimizing for the wrong things, and less prone to re-work.
Specifically you've said that:
* it's wrong to think that knowing about HW, compilers/interpreters, OSes and high-perf architecture will in fact help you "design better (performing?) code in the first place".
* changing goals from the sales team has a big impact on the performance optimisations and this happens frequently
* in your experience taking a poorly performing prototype and optimising it iteratively was a successful strategy. Poorly performing, as an example, might be 10x too slow.
* "It’s not only possibly to refactor for performance after the fact, but dramatically easier to do so, less risky in terms of optimizing for the wrong things, and less prone to re-work."
My experience doing C++, Java, JS mostly on embedded and mobile does not match your above statements. I'm not an optimisation expert and in fact this is not even my main work area, but I've seen plenty of catastrophic decisions which hobbled the performance of systems and applications without any hope of reaching a fluid processing workflow besides an effort-intensive rewrite. Furthermore, in those situations the development team was significantly slowed down by the performance problems.
In one case an architectural decision was made to use a specific persistency solution in a centralised way for the entire platform and this became a massive bottleneck. Good luck optimising that iteratively, sequentially or any other way. Languages can have a huge impact on performance: in one project an inappropriate language was chosen; non-native languages usually trade memory usage for speed, and this caused problems with the total memory consumption that were never really fixed. I would argue that memory is a typical problem in embedded, along with disk I/O, GPU usage and everything else, not even close to all performance problems can be reduced to CPU usage (or using SQL properly as someone else unhelpfully quipped).
How many LoC do your projects typically have and what kind of languages and technologies do you use? I'd be interested to hear if the heavy lifting is done by library code or your own code and if you're able to easily scale horizontally to tackle perf problems.
And... how do changing sales goals every two weeks affect performance? Is this some stealth start-up situation? :)
For instance, look at the Big Ball of Mud design. When you are looking at a Big Ball of Mud, these per module performance tests are difficult or impossible to maintain. It’s quite common to see a flame chart with high entropy. Nothing “stands out” after the second or third round of tweaking. Yes there are ways to proceed at this point, but they don’t appear in the literature
Haven’t had as much luck with larger teams. Too many chefs and more churn to deal with.
It's a plus to have an understanding of advanced topics like the workings of compilers, but when the foundations are lacking, you're shot.
When developers lack a basic grasp of basic data-structures, it harms not only performance, but complexity, readability, maintainability, code-density, and just about everything else we care about.
Knuth made his comment about optimization back when computing was about inner loops. Speed up the inner loop, and you're done. That's no longer the case. Today, operational performance problems seem to come from doing too much stuff, some of which may be unnecessary. Especially for web work. So today, the first big question is often "do we really need to do that?" Followed by, "if we really need to do that, do we need to make the user wait for it?" Or "do we need to do that stuff every time, or just some of the time?"
These are big-scale questions, not staring at FOR statements.
These days, things are often just not so in your face and a lot of "don't worry about it" advice. Which is often not bad advice in terms of getting things working. But eventually you do find you have to worry about it. Sometimes those worries happen far too late in bigger projects. So I think these Rules are pretty good. I'd also add in benchmarking very simple aspects of the toolset you are using to get an expectation of how fast things should be able to go. Often I have found (especially in the web world) someones expectation of how fast they think something can go is way too low because they have already performanced bloated their project and think its approximately normal.
If you want to run something like Windows 10 in a full-system emulator that is something like valgrind, performance matters. For each instruction emulated, you might need to run a few thousand instructions, and you can't get magical hardware that runs at 4 THz. Right from the start, you're deeply in the hole for performance.
Consider the problem of emulating a current-generation game console or smartphone. You can't give an inch on performance. You need to fight for performance every step of the way.
Just recently, I did a rewrite of an ARM emulator. It was all object-oriented nonsense. I haven't even gotten to profiling yet and the new code is 20x faster. Used well, C99 with typical compiler extensions can be mighty good.
It's important to have a feel for how the processor works, such as what might make it mispredict or otherwise stall. It's important to have a feel for what the compiler can do, though you need not know how it works inside. You can treat the compiler as a black box, but it must be a black box that you are familiar with the behavior of. When I write code, I commonly disassemble it to see what the compiler is doing. I get a good feel for what the compiler is capable of, even without knowing much about compiler internals.
The key thing in optimization is summed up by the old adage "you can't make a computer run faster; you can only make it do less." All of those things that make the dev experience nicer use CPU cycles. The more cycles that are needed, the longer your app takes to do things, and the slower it seems.
For most apps that doesn't actually matter because your app is idle 99.9% of the time, but it's good to be able to fix things in when it does.
Tempers his universals a bit.
In general, when working on web apps, which is mostly what I do, you don't gotta be quite that ambitious I think. On the other hand, you can't be _totally blind_ either, I've worked on some web apps that were disasters performance-wise.
But in general, while I gotta keep performance in mind all the time (okay you're right OP), I don't really gotta be _measuring_ all the time. The top 3% usually totally gets it.
But, when I worked on an ETL project -- performance performance performance all the way. Dealing with millions of records and some expensive transformations, the difference between an end-to-end taking 6 hours and taking 4 hours (or taking one hour! or less!) is _huge_ to how useful or frustrating the software is. And I had to start at the beginning thinking about how basic architectural choices (that would be hard to change later) effected performance -- or it would have been doomed from the start.
Certainly a game engine renderer is also more the latter.
But I don't know if you need _that_ level of performance focus on every project.
Interestingly it was working on an ETL project that drove me to learning Rust (my first low-level language). I tried to implement it in node, and it wasn't anywhere close to being fast enough.
Web in particular as an ‘OS’ sitting on top of an actual OS often gets it in the neck for being a resource hog and it’s not just the browser teams at fault there. The underlying assumption of do whatever, things are good enough and we have enormous amounts of processor power doesn’t help.
I’d argue that if we’re truely making software for people it should have as small an impact on their machines as possible. Or how much energy would we save globally if our code in data centres was more efficient?
And I agree with you on quantity ‘vs’ quality. A team that is faking it the whole time will never make it. Building the capacity of the team to deliver code at a certain quality bar (that is, to stop faking it) keeps the project from grinding to a halt in year three or four.
Web 2.0 in a nutshell
- It's slower than my speed of thinking / inputting. If I can press keys faster than they appear on the screen, it's completely broken.
- I can no longer have all the applications I need opened simultaneously, because together, they exhaust all the system resources. Even though I have a faster computer now, and 5 years ago, equivalent set of applications worked together just fine.
- My laptop/phone battery seems to be down to 50% in an hour.
- Your webpage takes 5+ seconds to load, even though it has just a bunch of text on it.
- Your webpage is slowing down / hanging my browser.
- I'm on a train / in a shopping mall, and have spotty connection. I can't load your webpage even though if I serialized the DOM, it would be 2kb of HTML + some small images, because of all the JS nonsense it's loading and doing.
Memory usage sure will help but it is mudding water more than more specific user-centric metrics. Sometimes for business applications(Slack) feature richness and in-app performance is more important than memory usage. It all depends on website/application and throwing tantrum about memory usage do not help.
Speed matters to end users. 12 Mb will not load in under a second for most users. Unless you absolutely dominate the field or have some specific redeeming feature, your users will move to your competitor services.
I'd like to refine the advice given a little bit, an approach I like to call "mature optimization". What you need to do ahead of time is primarily to make sure your code is optimizable, which is largely an architectural affair. If you've done that, you will be able to (a) identify bottlenecks and (b) do something about them when the time comes.
Coming back to the Knuth quote for a second, not only does he go on to stress the importance of optimizing that 3% when found, he also specifies that "We should forget about small efficiencies, say about 97% of the time". He is speaking specifically about micro-optimizations, those are the ones that we should delay.
In fact the entire paper Structured Programming with goto Statements[1] is an ode to optimization in general and micro-optimization in particular. Here is another quote from that same paper:
“The conventional wisdom [..] calls for ignoring efficiency in the small; but I believe this is simply an overreaction [..] In established engineering disciplines a 12% improvement, easily obtained, is never considered marginal; and I believe the same viewpoint should prevail in software engineering."
That said, modern hardware is fast. Really fast. And the problems we try to solve with it tend towards the simple (JSON viewers come to mind). You can typically get away with layering several stupid things on top of each other, and the hardware will still bail you out. So most of the performance work I do for clients is removing 3 of the 6 layers of stupid things and they're good to go. It's rare that I have to go to the metal.
Anyway, if you're interested in this stuff, I've given talks[2] and written a book[3] about it.
[1] http://sbel.wisc.edu/Courses/ME964/Literature/knuthProgrammi...
[2] https://www.youtube.com/watch?v=kHG_zw75SjE&feature=youtu.be
[3] https://www.amazon.com/iOS-macOS-Performance-Tuning-Objectiv...
Those who slam spaghetti code. Posit: Lasagna is just spaghetti flavored cake. Too many abstracted layers to fulfill a request. Down the layers, & back up, just to fulfill a simple request.
Autoloading can be expensive as well for I/O until cache is involved, especially with large code pools. Caching isn't optimization.
Trim the fat, reduce layers, use leaner pasta & or less special sauce.
If you've started tweaking costs/time from the ingredients & cooking process (lower level, OS, daemons, etc.) to start then move onto frameworks/libraries; it's less to consume & healthier. Ie., cache invalidation is much faster which should be at the end of your optimization journey.
Fundamentals are being abstracted away daily, while it's great for rapid prototyping & easier maintenance of code. It's imperative to understand problem spaces before delivering a solution.
A very highly recommended book is:
The Elements of Computing Systems: Building a Modern Computer from First Principles
https://www.amazon.com/dp/B004HHORGA/ref=cm_sw_r_cp_awdb_t1_...
The demo scene is a very good example to attempt to mimic with the culture of optimization. It's been bragging rights way early on. https://www.pouet.net/ granted hardware is much faster than it was back in the olden days. But a quick note from admiring their creations you get a taste for older hardware & milking every cycle you can. Maybe forcing younger up & coming devs to use older hardware means they'll appreciate it more & you'll know on current hardware it'll fly.
Another thing to think of is the von Neumann bottleneck & how it was solved (partially) with cache levels or Harvard architecture. I/O is a basis for optimization.
"There's no sense in being precise when you don't even know what you're talking about."
https://en.wikipedia.org/wiki/Von_Neumann_architecture
With all of the above said, I'm agreeing whole heatedly with the article & yourself as it's nice to see others focused on this as it seems to be a dieing breed.
I'll leave this here for web developers: http://motherfuckingwebsite.com
https://iarapakis.github.io/papers/TOIS17.pdf
https://skipjaq.com/assets/files/Why%20Fast%20Matters%20-%20...
I've seen it given as an answer on StackOverflow, even when the question is not "should I optimize this?" but more like "is X faster than Y?"
We need to stop parroting these valuable, but not absolute mantras and use common sense.
- write for clarity with an architecture that doesn't greatly impede performance
- have good habits, always use datastructures that work well at both small and larger scales
whenever readily available (e.g. hash tables, preallocating if size is known)
- think longer about larger decisions (e.g. choice of datastore and schema, communication between major parts)
- have some plans in mind if performance becomes an issue (e.g. upgrade instance sizes, number of instances)
and be aware if you are currently at a limit where there isn't a quick throw money at the problem next level
- measure and rewrite code only as necessary taking every opportunity to share both
why and how with as many team members as feasibleI came here basically to say something similar to this. The most important metric is to have a design in the beginning that attempts to identify where the problems (Critical paths at a high level) are going to be and avoids them. That doesn't necessarily mean the initial versions are written to the final architecture, but that there is a plan for mutating the design along the way to minimize the overhead for the critical portions.
Nearly every application I've ever worked on has had some portion that we knew upfront was going to be the performace bottleneck. So we wrote those pieces in low level C/C++ generally really near (or in) the OS/Kernel, and then all the non performance critical portions in a higher level language/toolkit. This avoided many of the pitfalls I see in other projects that wrote everything in Java (or whatever) and the overhead of all the non-critical portions were interfering with the critial portions. In networking/storage its the split between the "data path" and the "control path", some other products I worked on had a "transactional path" and a control/reporting path.
Combined with unittests to validate algorithmic sections, frequently the behavior of the critical path could be predicted by a couple of the unittests, or other simple metrics (inter-cluster message latency/etc).
I work on something that uses a lot of immutables with copy-modify operations. They never show up in a profiler as a hot spot. The most surprising hot spot was a default logger configuration setting that we didn't need. Other hot spots were file API calls that we didn't know we're slow.
I think what's more important is to use common sense in the beginning, and optimize for your budget. Meaning: Know how to use your libraries / apis, don't pick stupid patterns, and only do as much optimization as you have time for.
Sometimes an extra sever or shard is cheaper than an extra programmer, or gets you to market on time. Sometimes no one will notice that your operation takes an extra 20ms. Those are tradeoffs, and if you don't understand when to optimize for your budget, you'll either ship garbage or never ship at all.
> Sometimes an extra sever or shard is cheaper than an extra programmer, or gets you to market on time.
Sure, you're bailing yourself out by burning money. That's fine if it's all contained on your backend. My problem starts when similar situation happens on frontend - in the JS code of the website, or in the mobile app. Too often developers (or their bosses) will say "fuck it, who cares", as if their application was the only thing their customers were using on their machines. The problem with user-end performance is that suddenly, I can only run 3 programs in parallel instead of 30, even though I just bought a new computer/smartphone - because each of those 3 programs think they have the machine for themselves.
I have also felt it would be a fun bingo game in a year to see when a famous quote of someone would come up. This Knuth quote would definitely be on there.
Most of those pages will bubble up when you do your first profiling session anyway.
You can get away with good data structures/good sql queries and a little big O analysis almost everywhere.
Premature optimization, premature nines of stability, premature architecture and abstraction are as evil as ever. They all distract you from moving forward and shipping.
Of course, if your product is BLAS library, database, compiler, web browser, operating system or AAA video game, that does not apply. I mean, for most of us "profile often" is a terrible advise.
(edit: spelling, clarifications)
So design databases and algorithms for performance from day 1 & understand how the data needs to be structured? You'd have to verify the assumptions you made about the data were correct and profile often if you didn't want to worry about performance regressions. Bad enough regressions are a failed product and you can't ship something that could never get fast enough without a rewrite.
I don't think everyone in this thread has the same concept of what optimisation means. It doesn't all have to be obfuscating bit-fiddling. Even identifying the important paths is optimisation.
The 10x dev is the dev that creates 10% the problems other devs create.
Thinking ahead is a skill the industry at large unfortunately seems to lack
There are also a lot of times when it doesn’t matter, possibly the majority of the time in some domains. I’m working on a project now where the answer takes a couple of seconds to generate but it isn’t needed for minutes so spending time to make it faster would be a waste of my clients money.
Hrmm. In my experience very good programs also have very flat profiles. I don’t think a flat profile is indicative of bad performance culture.
1. Optimize only if needed.
2. Premature optimization is the root of all evil.
I saw rule 2. ignored almost daily at a job - putting caches where it doesn't matter, taking days on a feature because of analysis paralysis, colleges thinking about using int instead of Integer or not creating another function because of 'overhead'.
I think these are wise rules - of course not when you use a 2 MB js library for an uppercase() function. That is madness.
But the decision if you should use an arraylist or a linkedlist is unimportant almost every time. Of course there is that 1% when it matters and these rules are about the other 99%.
Good software is a multifaceted effort, and great software takes care of the important parts with attention to detail where relevant: great games libraries don't add significant overhead to frame time, great filesystem libraries don't increase read time, great security libraries don't expose users to common usage pitfalls creating less secure environments than had you used nothing at all.
It happens to be that optimization gets deprioritized at the expense of other things, where "other things" in this context is some category I fail to pin down because PMs don't give a shit about what that other category could be, and instead just care that whatever you're working on is shipped to begin with.
Great software developers will respect the important parts, and still ship. And yes, it's always easier to do this from the start than it is to figure it out later. Many things in life are this way.
I have a soft spot for performance, though, so I care about this message. One day hardware will reach spacial, thermal, and economic limits and when that day comes, software engineers will have to give a shit, because too many sure as hell don't seem to give a shit now.
Everything should be subject to cost/benefit!
Corollaries: (...don't do that!)
- If you paint yourself into an untenable corner, you lose!
- If you plant a time bomb that explodes and kills you, you lose!
- If you sink yourself too deeply into technical debt, you die! You lose!
Avoiding pre-optimization is just the flip side of the intelligent cost/benefit analysis coin. Don't start writing hyper-optimized code everywhere. However, also don't architect your real-time game system such that making string comparisons is inextricably the most common operation.Here's a solution that I've found. It's not foolproof, but it will get you out of trouble quite often. Code such that you can change your mind. HN user jerf's "microtyping" technique in Golang let me do that with my side project. I committed the egregious error I mentioned above, of using string identifiers for the UUID of my MMO game entities. But because I followed the "microtyping" technique and did not directly use type string, but rather used ShipID, I could simply redefine:
//type ShipID string // old bad way
type ShipID struct { // new way
A int64
B int64
}
Where possible, your code changes should be bijections. Renamings should be bijections and never surjections. The bigger your changes, and the more automation is involved, the more you should hew to bijective changes. A ---> a
B ---> b
The following is not a bijection. It is not easily reversible. A ---> b
B ---> b
So for example, if I rewrite all occurrences of "ShipID" to be "string," those occurrences get lost among all of the other uses of "string." I could always go back to git and back out the change, but what happens in the future, when those changes have become interspersed with other changes?They're two completely different schools of thought and may work well in either scenario. It depends a lot on your background, and your current context what way you are going to write code.
The truth is, you have at least three distinctive groups on the performance spectrum: people who are obsessed, people who treat it as one of the things to prioritize, and people who never do it (and tell you it's never the time to do it). The truth is, a lot of performance problems come from imperative code, and functional doesn't mean slow if you know what you're doing. The truth is, most big performance issues can be solved by not doing stupid shit and taking an occasional look at the resource usage. The former requires a little knowledge of how computers and your tools work. The latter requires care about end users, which seems to be in short supply.
I was making an effort to be unbias, by making clear the "good attributes" of each side.
I wasn't at all trying to make that harsh of a distiction. In fact I was trying to point out the ridiculousness of it. What I was trying to point out with irony, I should have said clearly what my opinion is:
If you're too concerned with speed, and you optimize early, I think your code style is less than ideal. Essentially your code is messed up to the point that it's too difficult to go back to make optimizations if necessary.
I think the reason functional programmer's don't talk about optimization as much is because they don't need to. It's a completely different paradigm.
So much like politics, if you only listen to one side, you're going to get messed up ideas of the way the world works.
I hope this offers a better explanation