Do you write your code then optimise it? Or do you write an optimised code from the beginning.
I always believe in writing optimised since I really dont like to rewrite code, But please share your thoughts.
Do you write your code then optimise it? Or do you write an optimised code from the beginning.
I always believe in writing optimised since I really dont like to rewrite code, But please share your thoughts.
There's a simple order rule of three:
The rule of thumb is this one (emphasis mine):
Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
-- Donald E. Knuth, "Structured Programming with
go to
Statements"
Now, this doesn't mean you should write inefficient code. You should write efficient code if it doesn't take much more time than inefficient code. If you can do 1 SQL request instead of 100, please do so. If it doesn't take you much more time, that is.
This code might not be used very often, so it's actually not a bottleneck at all, even though it might seem inefficient. If writing it in an efficient way means spending too much time, there is no added-value to your business.
Then of course, if you have to optimize something because it's slow, never forget to profile first.
Some links that might interest you:
Are you suggesting to do premature optimization?
The code is fast when it matches the performance non-functional requirements. Until those requirements are fulfilled, you don't have to care about performance: there are much more important things to care about, like the quality of your code, the architecture, etc.
Once the non-functional performance requirement is broken by your code, it means that it's slower than what is acceptable/desirable. At this point, you should:
Profile your code (instead of guessing where the bottleneck is, since we always get it wrong),
Optimize it until the test corresponding to the requirement passes again.
Write optimized when you know for sure that it will have an effect and is justified in the mean of code readability.