When is optimisation premature?

Don Knuth started the literate programming movement because he believed that the most important function of computer code is to communicate the programmer’s intent to a human reader. Any coding practice that makes your code harder to understand in the name of performance is a premature optimization.

Certain idioms that were introduced in the name of optimization have become so popular that everyone understands them and they have become expected, not premature. Examples include

  • Using pointer arithmetic instead of array notation in C, including the use of such idioms as

    for (p = q; p < lim; p++)
    
  • Rebinding global variables to local variables in Lua, as in

    local table, io, string, math
        = table, io, string, math
    

Beyond such idioms, take shortcuts at your peril.

All optimization is premature unless

  • A program is too slow (many people forget this part).

  • You have a measurement (profile or similar) showing that the optimization could improve things.

(It’s also permissible to optimize for memory.)

Direct answer to question:

  • If your “different” technique makes the program harder to understand, then it’s a premature optimization.

EDIT: In response to comments, using quicksort instead of a simpler algorithm like insertion sort is another example of an idiom that everyone understands and expects. (Although if you write your own sort routine instead of using the library sort routine, one hopes you have a very good reason.)

Leave a Comment