Refactoring and Performance. Ignore it: mostly.20 Dec 2018
Martin Fowler in Refactoring2:
Firstly, I know readers will again be worrying about performance with this change, as many people are wary of repeating a loop. But most of the time, rerunning a loop like this has a negligible effect on performance. If you timed the code before and after this refactoring, you would probably not notice any significant change in speed—and that’s usually the case. Most programmers, even experienced ones, are poor judges of how code actually performs. Many of our intuitions are broken by clever compilers, modern caching techniques, and the like. The performance of software usually depends on just a few parts of the code, and changes anywhere else don’t make an appreciable difference.
But “mostly” isn’t the same as “alwaysly.” Sometimes a refactoring will have a significant performance implication. Even then, I usually go ahead and do it, because it’s much easier to tune the performance of wellfactored code. If I introduce a significant performance issue during refactoring, I spend time on performance tuning afterwards. It may be that this leads to reversing some of the refactoring I did earlier— but most of the time, due to the refactoring, I can apply a more effective performance tuning enhancement instead. I end up with code that’s both clearer and faster.
So, my overall advice on performance with refactoring is: Most of the time you should ignore it. If your refactoring introduces performance slowdowns, finish refactoring first and do performance tuning afterwards.
Some great thoughts on refactoring and worrying too much about performance. (emphasis mine) I’ve been contributing a lot lately to the great site Exercism and I see this quite a bit - worry about writing fast code vs writing clear code - and all without ever benchmarking anything.
It’s possible to do this “in your head” guessing a bit more with time and experience, but as Martin said it’s still often never as simple as you think. And often your best efforts today can be foiled by a new compiler optimization or future change to the virtual machine. Better to:
- Write clear code that reveals the intent.
- Try to avoid anything too ridiculous (i.e., looping 1,000 times when once would do).
- Optimize only the “hot spots” that reveal themselves to be problematic.
- Attack the hot spots with the help of code profiling and detailed benchmarking.
Get the book:
Refactoring - Improving the Design of Existing Code