LWN.net Logo

Infinite loops as bad taste

Infinite loops as bad taste

Posted Mar 5, 2007 6:15 UTC (Mon) by landley (guest, #6789)
In reply to: Infinite loops as bad taste by pr1268
Parent article: Re: [GIT PATCH] HID and USB HID update for 2.6.21-rc2

> Actually, I was taught that for(;;) is faster than while(1)

And circa 1984, this was true.

Compilers change. Optimizers change. Hardware changes drastically. (2
megabytes of L2 cache?)

x=5;
if (blah) x=7;

This is now generally faster than:
if (blah) x=7;
else x=5;

Why? Branch prediction with conditional assignments to avoid bubbles in
the pipeline. Taking a branch is noticeably slower than doing an extra
(unnecessary) assignment, and the if/else means _either_ way you branch.

However, 90% of the time you don't have to _care_ because your compiler
knows about conditional assignment and will rewrite variant #2 to look
like variant #1.

And if you religiously write #1 it's possible that in 5 years new hardware
will show up that makes the _previous_ way of doing it the fast way again.
(Once upon a time, rotating a point around a circle, programmers
precalculated a lookup table of all 360 positions to avoid doing slow
trigonometry math. Then processors got a clock multiplier faster than the
motherboard, and the lookup table became slower than doing the math
because it didn't fit in cache. Then caches got big again, and the lookup
table fit in memory again... It's a pendulum. There IS no one right
answer. Even if you know _everything_ the compiler is doing, if your code
is any good it could easily outlive that specific processor and compiler
version. (And if it isn't any good, what's the point in trying to
optimize it?)

Remember Ken Thompson's "When it doubt, use brute force" because it's darn
good advice.

That said, I use for(;;) because I think it's cleaner. (It lies to the
compiler slightly less; while(1) smells like if(1), and even though both
tests get optimized out I don't like having it there without a reason.)


(Log in to post comments)

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds