Fastest type of loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Fastest type of loop

Post by GeXus »

Just wondering what the fastest type of loop is, is it the while loop?

Thanks!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I think it's a bit dependant on what your needs are. Generally, while() is typically faster than foreach().
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Re: Fastest type of loop

Post by Roja »

GeXus wrote:Just wondering what the fastest type of loop is, is it the while loop?

Thanks!
http://www.blueshoes.org/phpBench.php
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

excellent, thank you!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Although those benchmarks are more about optimizing arrays than loops. I image the looping speed is actually very similar with while() and for() slightly faster than foreach() as feyd said.
(#10850)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If in need of an ultrafast infinite loop, I always use

Code: Select all

for(;;)
{
  // code here
}
This is a carryover from my C days, but I believe it still stands as the fastest possible loop. Why? Because there's no checks or code to run for the language at any point other than that inside the loop. Granted, it is microscopic amounts of time difference usually, but when you're running very time critical code, you need really tight loops.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

And old Pascal programmers would probably do:

Code: Select all

while(1) {
...
}
(#10850)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

It's been a very long time, but i think this looks more like the Pascal style ;)

Code: Select all

while true do
begin
  statements;
end;
Post Reply