[eluser]Xeoncross[/eluser]
I just rediscovered PDO and the default PHP mysql(i) classes and I started working with them again after having so much fun with the great Active Record classes CI provides. However, I have to use a while loop again as foreach doesn't work with all result types and such.
That got me thinking - just what is the difference between them? So, I just spend all afternoon til now (11pm) benchmarking and testing. So take a look at what I found. Despite lots of references online to foreach being faster than while - it isn't when you are dealing with multidimensional arrays/objects like database results.
All of these results are iterating over 1000 array elements with each element containing an array of 4 numbers (1 to 1000). So the array we are using is two levels deep with a total of 5000 items in the array.
I tried as best as I could to make sure that each iteration did NOT inherit or pass on values. However, I still do not trust the memory ratings completely.
The test was performed on PHP 5.2.8 on an XP Core2Quad. PHP4 will have different results for sure.
Code:
Just iterating over them and doing nothing with the values.
Memory Time Array ID
584 0.26062202453613 foreach_n
560 0.01010799407959 whilelist
584 0.30483794212341 foreach_k
888 0.29932808876038 foreach_r
Peak Useage: 595824 bytes
Taking the array keys and values and placing it in another array
Memory Time Array ID
63824 0.67118906974792 foreach_n
464 0.010374784469604 whilelist
528 0.5559618473053 foreach_k
1984 1.1413900852203 foreach_r
Peak Useage: 52736960 bytes
Added the for loop and went though every key => value and changed it to array('string', 'string)
Memory Time Array ID
48840 1.2370409965515 foreach_n
5312 0.022001028060913 whilelist
768 1.2729561328888 foreach_k
293264 1.169282913208 foreach_r
464 0.0017411708831787 forloop_n
Peak Useage: 891352 bytes
The "Array ID" is as follows:
Code:
foreach_n = foreach($object as $v1) {
foreach_k = foreach($object as $k3 => $v3) {
foreach_r = foreach($object as $k4 => &$v4) {
whilelist = while (list($k1,$v1) = each($object)) {
for = $size = count($object); for ($i=0; $i<$size; $i++) { $v5 = $object[$i]; ...
So does anyone have anything to add to this? I never knew that while was so fast, let alone that for was blazing! And no, "it is too small a difference to mater" is not a valid answer.