Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!cornell!batcomputer!itsgw!steinmetz!uunet!mcvax!cernvax!hjm From: hjm@cernvax.UUCP (Hubert Matthews) Newsgroups: comp.lang.c Subject: Efficient programming - a maxim Message-ID: <840@cernvax.UUCP> Date: 5 Oct 88 11:30:51 GMT References: <836@proxftl.UUCP> <3105@hubcap.UUCP> <1700@dataio.Data-IO.COM> Reply-To: hjm@cernvax.UUCP (Hubert Matthews) Organization: CERN European Laboratory for Particle Physics, CH-1211 Geneva, Switzerland Lines: 50 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