449,149 Members | 1,022 Online
Need help? Post your question and get tips & solutions from a community of 449,149 IT Pros & Developers. It's quick & easy.

# Speed of do while

 P: n/a We can read this comment at php.net jon05-Nov-2003 10:06According to my tests, the "do...while" control structure actually seems to be ~40% faster than the "for" control structure. At least using PHP v4.0.6on a few fairly modern Linux machines. I used a the getmicrotime function as defined at http://www.php.net/microtime I tested the following 5 scenarios, including two different ways of calling a "for" loop. The less ordinary way to call "for", I'll call "altfor". Here >are the code scenarios for different ways from counting from 0->(\$num-1), in my case \$num = 10000: // 'altfor': \$a=0; for (; \$a<\$num;) { \$a++;} // 'for': for (\$a=0; \$a<\$num; \$a++) {} // 'foreach': foreach (range(0,\$num-1) as \$a ) {} // 'while': \$a = 0; while (\$a < \$num) {\$a++;} // 'do': \$a = 0; do {} while (++\$a < \$num); Each scenario is called in random order, and here is a typical result: Average times for 100 iterations of each loop: altfor, do, for, foreach, while.All loops are incremented from 0 to 9999. altfor: 0.036882833242416 seconds, 138.25 percent of ~ 0.0267 seconds do: 0.026678282022476 seconds, 100.00 percent of ~ 0.0267 seconds for: 0.037308998107910 seconds, 139.85 percent of ~ 0.0267 secondsforeach: 0.064857139587402 seconds, 243.11 percent of ~ 0.0267 seconds while: 0.036508817672729 seconds, 136.85 percent of ~ 0.0267 seconds...so to be clear, I ran "for", et all, from 0->9999. This was done 100 times. Above are the average times for those 100 tests of loops of 10,000. I >have run my script multiple time on several different Linux systems here at my work. All w/ similar results... As anyone tryed to see if thats true and do...while is about 40% faster than for ? Jul 17 '05 #1