Just a quickie thought this time around, not too heavy:
Avoiding micro-optimizations
What's a micro-optimization, you may ask? It's applying a local-in-scope rule about optimization to your code without actually testing to see if it makes any difference to the performance of your application as a whole. Micro-optimizations are generally cast as never-to-be-broken rules, or even as items in some coding standards document.
Sometimes we refer to them as premature optimizations. The root of all evil, to quote Knuth.
Examples are easy to find: always using for
instead of foreach
, appending to a StringBuilder object instead of string concatenation, avoiding small methods to minimize the call time.
Now, before you start huffing and puffing, I'm not advocating abandoning these optimizations, or saying that they are inherently evil, or anything like that. All I'm saying is that you should initially write code to be as clear as possible. That implies that your code should be readable, simple and understandable. Writing clear code gives you the best chance of creating provably correct software and of creating code that is easier to optimize. Writing clear code provides the best opportunity for enhancing maintainability. Clear code is generally more flexible and better able to adapt to future needs and changes. Consider using refactorings guided by software metrics to simplify your code. Consider using your skills as a developer to identify and remove code smells.
And it's only after your code is written that you get to profile it to test its performance within the application. Only then do you get to analyze the hot spots in your application as a whole. Only then do you get to formulate a thesis ("replacing this simple-to-read foreach
with a slightly harder to read for
loop will improve the performance of my application as a whole") and then test it with the real application. Only then should you accept code changes that have a measurable change in your application's performance. Only then should you reject failed theses and revert your code to the simpler-to-read version.
Don't change your code to suit some optimization fad: change it to improve its performance.
Having written it, I now wonder: when do micro-optimizations become so familiar that they are clear and readable? As an example, I would venture to say that using a StringBuilder is actually more legible than writing a set of statements that do string concatenation. Or someInt >> 1
becomes just as readable as someInt / 2
. Hmm.
Free DevExpress Products – Get Your Copy Today
The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the
DevExpress Support Center at your convenience. We’ll be happy to follow-up.