Friday, November 28, 2008

PHP Loop Benchmarking - WHILE vs FOR

I was very bored today, when I suddenly realised that I should do some benchmarking for PHP myself. I created a script (can be found at thephpcode pastebin: http://thephpcode.pastebin.com/f80e53fe) and run it on my xampp localhost.

In the php benchmarking script, i am comparing 3 loops: FOR, WHILE and FOREACH. Amazingly, but not surprising, WHILE loop is the fastest compared to FOR and FOREACH, and as expected FOREACH is the slowest.

This is my output:
0.000854015350342 seconds
// for the FOR loop with 10000 times
0.000696897506714 seconds
// for the WHILE loop with 10000 times
10000 elements
// the number of elements in the array
0.00111794471741 seconds
// for the FOREACH loop with 10000 times


I read about the WHILE loop on Javascript that WHILE is faster than FOR, but I didn't know that the same thing applies in PHP too. Well, here's a learning point for all of us.

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

2 comments:

gamers2000 said...

Hehe lemme test it out in java and see if it applies :D

thephpdeveloper said...

lols sure you can try it out in Java ^^