Page 1 of 1

Fastest type of loop

Posted: Sun Apr 09, 2006 5:31 pm
by GeXus
Just wondering what the fastest type of loop is, is it the while loop?

Thanks!

Posted: Sun Apr 09, 2006 5:40 pm
by feyd
I think it's a bit dependant on what your needs are. Generally, while() is typically faster than foreach().

Re: Fastest type of loop

Posted: Sun Apr 09, 2006 5:57 pm
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

Posted: Sun Apr 09, 2006 6:09 pm
by GeXus
excellent, thank you!

Posted: Sun Apr 09, 2006 10:04 pm
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.

Posted: Sun Apr 09, 2006 10:09 pm
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.

Posted: Sun Apr 09, 2006 10:17 pm
by Christopher
And old Pascal programmers would probably do:

Code: Select all

while(1) {
...
}

Posted: Mon Apr 10, 2006 6:56 am
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;