jfh@killer.UUCP (11/04/87)
In article <44177@beno.seismo.CSS.GOV>, rick@seismo.CSS.GOV (Rick Adams) writes: > Even a mediocre compiler should be able to recognize that > a++; > is equivalent to > ++a; > if there is no assignment, etc. > > There is really no excuse for not making this trivial optimization. You should > not have to depend on the user doing it. > > --rick I really hadn't expected Rick to come up with that one. Guess working for the government was gone to his brain ... (Sorry, couldn't pass up a anti-government dig ;-). I have recapped the story for the comp.lang.c folks. The code in question was while (a--) vs. while (--a) ; ; which is the same as while (a-- != 0) vs. while (--a != 0) ; ; the pre-decrement loop makes one less trip since the value of `a' is decremented _prior_ to the test (not actually though). Consider the case where a == 1. The --a will equal 0 and the test will fail. In the case of a--, the value _prior_ to the decrement is used and the test will pass, so the loop gets executed. To be the same, assuming `a' is not used in the loop, you would have to code a++; while (--a) ; to get the same number of trips (assuming overflow was not a problem). This would be a big win if the code in the loop was very small and the value of `a' was large. I wouldn't do it since the time savings would be small, and the code a kluge. Of course, documentation helps. - John. -- John F. Haugh II HECI Exploration Co. Inc. UUCP: ...!ihnp4!killer!jfh 11910 Greenville Ave, Suite 600 "Don't Have an Oil Well?" Dallas, TX. 75243 " ... Then Buy One!" (214) 231-0993
karl@haddock.ISC.COM (Karl Heuer) (11/06/87)
[Someone noted that "while (i--);" is slower than "while (--i);". It was pointed out that the former generates more instructions because of the extra work to save the old value of the counter. At least one person claimed that the postdecrement operator should be avoided for this reason; apparently he didn't notice that the value was being used, and that the two statements are not semantically identical. Rick Adams observed that, even if the value is not being used, the user need not be concerned with this optimization.] More than one person writes that an n-trip loop should be written ++n; while (--n) ...; I'm surprised that nobody has yet mentioned the idiom that I use: while (--n >= 0) ...; This has the speed of predecrement, and avoids the kludge of having an extra increment. It requires n to be a signed type, but that's not usually a problem. (Also, it doesn't have identical semantics if n is negative, but from the context I presume that this is not a concern.) Of course, the other way is to write do ...; while (--n != 0); [or] do ...; while (--n > 0); assuming n is known to be initially nonzero. Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint Followups to comp.lang.c only.