Wednesday, December 06, 2006

A peep into a good mail...

From: scs@eskimo.com (Steve Summit)
Newsgroups: comp.lang.c, comp.lang.c.moderated
Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ list)
URL: http://www.eskimo.com/~scs/C-faq/top.html

20.13: What's the best way of making my program efficient?

A: By picking good algorithms, implementing them carefully, and
making sure that your program isn't doing any extra work. For
example, the most microoptimized character-copying loop in the
world will be beat by code which avoids having to copy
characters at all.

When worrying about efficiency, it's important to keep several
things in perspective. First of all, although efficiency is an
enormously popular topic, it is not always as important 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
usually 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 seemingly "inefficient"
code may be quite efficiently compilable, and 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, one of the least
effective optimization techniques is to fuss with 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_.

No comments: