You are here: Re: For loop and while loop. which one is faster? « PHP Programming Language « IT news, forums, messages
Re: For loop and while loop. which one is faster?

Posted by Tim Streater on 03/27/07 10:01

In article <eu9m2t$af5$1@hercules.cohp1>,
Ivαn Sαnchez Ortega
<ivansanchez-alg@rroba-escomposlinux.-.punto.-.org> wrote:

> mgcclx@gmail.com wrote:
>
> > For loop and while loop. which one is faster?
> > I see many articles fighting over it and different people come up with
> > different results.
>
> Unless you're designing a compiler, don't worry about that. Worry about the
> algorithms instead.
>
> That said, the only possible difference between a for loop and a while loop
> is the jump prediction in your architecture's code instruction set. e.g.
> the processor can suppose that the condition for a while loop is going to
> be true, so it feeds the instructions after the conditional jump (that is,
> it's supposing that the jump condition will be successful) and starts
> running them in the first stages of the instruction pipeline, saving a
> couple of pipeline stages.
>
> Do you have to worry about processor pipelines and jump prediction? Not at
> all, unless you're into assembler, or heavy low-level programming. If you
> haven't understood a word of the last paragraph, don't worry about loop
> speed.
>
> In other words: trust your compiler (or JIT compiler, or interpreter). It
> knows about optimizations of conditional jumps better than you (the same
> applies to memory caching). Focus on the algorithmics if you want to
> shorten processor time.

This is quite right. I never worry about such things - that's the
computer's job.

I use whichever is appropriate - try, in other words, to give a hint to
yourself or whoever is going to look at that code in a year's time. If I
have n items and I want to do something for each of them, I use a for
loop. If I need to loop around until some condition is satisfied (maybe
one of several conditions in different parts of the loop), then I use a
while.

-- tim

 

Navigation:

[Reply to this message]


УдалСнная Ρ€Π°Π±ΠΎΡ‚Π° для программистов  •  Как Π·Π°Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ Π½Π° Google AdSense  •  England, UK  •  ΡΡ‚Π°Ρ‚ΡŒΠΈ Π½Π° английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Π‘Π°ΠΉΡ‚ ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ Π² Π‘Ρ‚ΡƒΠ΄ΠΈΠΈ Π’Π°Π»Π΅Π½Ρ‚ΠΈΠ½Π° ΠŸΠ΅Ρ‚Ρ€ΡƒΡ‡Π΅ΠΊΠ°
ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ΠΈΠ΅ ΠΈ ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΊΠ° Π²Π΅Π±-сайтов, Ρ€Π°Π·Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΠ½ΠΎΠ³ΠΎ обСспСчСния, поисковая оптимизация