One should not intentionally write slow code. But one should also beware obfuscation in the name of efficiency. Experienced programmers will tell you that premature optimization is the root of all evil; see also the rules of program optimization.

In "the value of a college degree - computer science", the following claim appears:

Compiler Design

In my opinion, this is the most useful of all the areas of Computer Science. Everything that is done by a programmer uses either an interpreter or a complier [sic] . The understanding of what happens to the code after it is entered is invaluable when trying to optimize the program. Take for example the following two segments of code:
main()                  |  main()
{                       |  {
  unsigned int i = 8;   |    unsigned int i = 8;
  unsigned int j;       |    unsigned int j;
  j = i / 2;            |    j = i >> 1;
  return j;             |    return j;
}                       |  }
The one on the right has 3 machine code instructions (Pentium produced by gcc -S) for the assignment to 'j', while the one on the left takes 9.
Claims such as these should be taken with a grain of salt. It's a rare compiler indeed that cannot recognise that a division by a constant might be replaced by an arithmetic shift.

So I did what they taught me in my computer science degree (no, I never took that Compilers course): I ran a test (on a Sun UltraSPARC-2 and on a Pentium III).

  • When compiling with gcc -S -O, both versions generate identical code. Examination reveals that i has been eliminated, and a direct load (the equivalent of j=4) substituted.
  • Adding a volatile modifier to i defeats this constant folding optimization; gcc -S -O still produces identical code. In all cases a shift is substituted for division.
  • Compiling without the -O flag yields different results! But this is a flawed test for two reasons:
    1. The only difference is that different registers are chosen for i and j; a shift is still compiled for both cases;
    2. If efficiency is important to you, you should compile with -O (optimization turned ON) anyway, and pay the price of longer compile times.
Yes, careful coding can make a difference. But no, almost all code is best left alone in its clear form!

Profile first, optimize after!

Log in or register to write something here or to contact authors.