Re:The Fallacy of Premature Optimization
by GuB-42 on Monday October 31, 2022 @02:58PM
(#33410907)
> Loads of performant code is really hard to read because it's full of magic that speeds things up.
That's if you go down to the lowest levels of optimization. The kind of things you see in compression, hashing, sorting, codecs,... Really hardcore optimization because otherwise, you wouldn't be able to watch that video at without turning your device into an heater, if at all.
But in more reasonable cases, simpler code often turns out faster. The less you do, the faster it runs, which is kind of obvious. Readable code is also a good thing for performance, if is easier to see and fix inefficiencies if the code is readable. A good part of performance problems are simply bugs: memory leaks, operations done several times for no reason, etc... and many others are fixable with no loss in readability, for example by using the proper data structure.
As for the last part, use a profiler, there is no point optimizing without a profiler. If you don't have a profiler, then good luck, it is doable, like investigating a crash without a stack trace is doable, but it is horrible.
One thing I do no matter what: always use the algorithm with the best big-O complexity available, unless you have a good reason not to. You may think you don't have enough data for that O(N^2) or worse to matter, but it can change, in fact, this is the most common type of change, and once you get in the zone, it can get really slow really fast, lookup "accidentally quadratic".
That's if you go down to the lowest levels of optimization. The kind of things you see in compression, hashing, sorting, codecs,... Really hardcore optimization because otherwise, you wouldn't be able to watch that video at without turning your device into an heater, if at all.
But in more reasonable cases, simpler code often turns out faster. The less you do, the faster it runs, which is kind of obvious. Readable code is also a good thing for performance, if is easier to see and fix inefficiencies if the code is readable. A good part of performance problems are simply bugs: memory leaks, operations done several times for no reason, etc... and many others are fixable with no loss in readability, for example by using the proper data structure.
As for the last part, use a profiler, there is no point optimizing without a profiler. If you don't have a profiler, then good luck, it is doable, like investigating a crash without a stack trace is doable, but it is horrible.
One thing I do no matter what: always use the algorithm with the best big-O complexity available, unless you have a good reason not to. You may think you don't have enough data for that O(N^2) or worse to matter, but it can change, in fact, this is the most common type of change, and once you get in the zone, it can get really slow really fast, lookup "accidentally quadratic".