Monday, August 24, 2009

PHP Arrays - End vs Indices

I've looked through the PHP Arrays function list lately while working on some php scripts that requires lots of interaction with Arrays. It came to me that the following 2 are the identical:

$value = end($array);
$value2 = $array[count($array)-1];

But which is more efficient?

In a test, I tested both with a 1000 elements array. A total of 5 tests were ran and an average of 0.00040926s for using end() and 0.00041699s for using $arr[count($arr)-1].

That was only a single dimension array. Which means that all the elements are non-arrays. The moment i ran on a 2 dimensional array, the test results differ! Again I ran 5 tests, and an average of 0.00070285s for using end() and 0.00040769s for $arr[count($arr)-1].

Why? end() has to move the internal pointer of the array all the way to the end of the array. However, end() is still useful for arrays whose keys are not numeric.

The codes for the test can be found on pastebin at http://thephpcode.pastebin.com/f7fa7d00c

No comments: