### Question 20.13

How can I make my code more efficient?

Efficiency, though a favorite comp.lang.c topic, is not important nearly as often as people tend to think it is. Most of the code in most programs is not time-critical. When code is not time-critical, it is far more important that it be written clearly and portably than that it be written maximally efficiently. (Remember that computers are very, very fast, and that even ``inefficient'' code can run without apparent delay.)

It is notoriously difficult to predict what the ``hot spots'' in a program will be. When efficiency is a concern, it is important to use profiling software to determine which parts of the program deserve attention. Often, actual computation time is swamped by peripheral tasks such as I/O and memory allocation, which can be sped up by using buffering and caching techniques.

Even for code that is time-critical, it is not as important to ``microoptimize'' the coding details. Many of the ``efficient coding tricks'' which are frequently suggested (e.g. substituting shift operators for multiplication by powers of two) are performed automatically by even simpleminded compilers. Heavyhanded optimization attempts can make code so bulky that performance is actually degraded, and are rarely portable (i.e. they may speed things up on one machine but slow them down on another). In any case, tweaking the coding usually results in at best linear performance improvements; the big payoffs are in better algorithms.

For more discussion of efficiency tradeoffs, as well as good advice on how to improve efficiency when it is important, see chapter 7 of Kernighan and Plauger's The Elements of Programming Style, and Jon Bentley's Writing Efficient Programs.

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback