Premature Optimization

Is it normal?

by Mite Mitreski / @mitemitreski

Premature optimization is the root of all evil (or at least most of it) in programming.

-Donald Knuth

The road to programming hell is paved with “best practices” applied too early. Very few abstractions, extractions, or architectures are inherently bad (although I’ll contend that a few are). But most of them are downright evil if applied before they’re called for.

-David Heinemeier Hansson, Winning is the worst thing that can happen in Vegas

S*** HN says

Add Back up image

Press down or up to navigate.

Real problem

Don't just conatenate strings use

StringBuffer/StringBuilder

Only partialy true

If you do this in a long loop or a function that calls a lot of different fuctions only than it makes sense

Object reference creation is expensive

          
            SomeObject x = null;
            for(int i = 0; i<1000;i++){
              x = someMethod();
              ...
            }
          
          

Initalize collection if you know the number of objects

          
            List xList = new ArrayList(1000);
            for(int i = 0; i<1000;i++){
              xList.add(...);
              ...
            }
          
          

Just add final and the code will run faster

          
            List xList = ...;
            for(int i = 0; i<1000;i++){
              final SomeObject o = xList.get(i);
              ...
            }
          
          
A common misconception is that optimized code is necessarily more complicated, and that therefore optimization always represents a trade-off. However, in practice, better factored code often runs faster and uses less memory as well. In this regard, optimization is closely related to refactoring, since in both cases we are paying into the code so that we may draw back out again later if we need to. We don't (yet) have PrematureRefactoring? regarded as CategoryEvil.

C2, Premature Optimization

The favourite
  • Make it work.
  • Make it right (the code is readable )
  • Make everything work.
  • Make everything right.
  • Use the system and find performance bottlenecks.
  • Use a profiler in those bottlenecks to determine what needs to be optimized.
  • Make it fast. You maintained unit tests, right? Then you can refactor the code mercilessly in order to improve the performance.

    -- Guillermo Schwarz

Optimization is normal as long as it does not hurt readability

That is all folks

note that faster is not always better