hjm@cernvax.UUCP (Hubert Matthews) (10/05/88)
Some advice on efficient programming is: Never do the same thing more than once That implies using temporary variables to hold the results of operations for later reuse. Also, it implies that testing the same condition when you know it hasn't changed is out such as in: while (loop_termination_condition) if (loop_invariant_condition) blah... else glurp... Replace it by: if (loop_invariant_condition) while (...) blah... else while (...) glurp... This scores on vector machines in particular. This is an example of the use of a corollary of the initial statement, which is: Make decisions as early as possible Deciding what *not* to do at an early stage can save a lot of work later. It also helps with error handling. Calculating new values from old values instead of starting from scratch is another example. One very common instance of this is the strength reduction performed by some compilers on array indexing; turning an array reference in a loop into a walking pointer rather than an offset from the beginning of the array is quicker since the position of the next element is easy to determine from the present position. Also, some of the newer (and faster) spreadsheets recalculate only those parts that are affected by a change rather than the entire sheet. Incremental compilers work this way too. Also, Don't do at run time what you can do at compile time You compile once, you run more than once. Therefore, don't repeat the same thing, do it just once. (Sizeof is useful in this respect.) All of this is obvious really, but I thought I'd try to condense the idea into a single sentence if possible. -- Hubert Matthews
mcdonald@uxe.cso.uiuc.edu (10/09/88)
>Some advice on efficient programming is: > Never do the same thing more than once >That implies using temporary variables to hold the results of operations for >later reuse. example: x = (a+b)*(c+d)-(c-d)/(a+b); versus t = a+b; x = t*(c+d)-(c-d)/t; I have checked this sort of thing, and larger examples, on many compilers, including vector machines, machines with poor optimizers, mediocre optimizers, and stupendous optimizers (VAX C). With a stupendous optimizer it of course doesn't matter one bit. With poor or mediocre optimizers, sometimes one is better, sometimes the other. You just have to try it. This is why hacks and tweaks have to come last, and are non-portable. Just like your momma taught you.