PHP Performance & Benchmarking: Random Array Element Access: rand() vs. array_rand()

Often during development you come upon a situtation where you have to randomly pick an element from an array. The PHP guys did us a favor and created the array_rand() function, but I suspected it wasn't as fast as it could be. Below are the comparisons between array_rand() and code that produces the exact same result using the rand() function.

Test Environment: Linux, Apache, PHP 5.2.17.

Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable. Each test was run 3000 times to get the average.

Comparisons

Using array_rand()

$array=array(1,1,2,3,5,8,13,21,34,55,89,1,1,2,3,5,8,13,21,34,55,89,1,1,2,3,5,8,13,21,34,55,89);
			
for($i=0; $i<1000; $i++)
{ 
	$randKey=array_rand($array);
	$randElement=$array[$randKey];
}

Using code using rand()

$array=array(1,1,2,3,5,8,13,21,34,55,89,1,1,2,3,5,8,13,21,34,55,89,1,1,2,3,5,8,13,21,34,55,89);

$arraySize=count($array);
for($i=0; $i<1000; $i++)
{ 
	$randKey=rand(0,$arraySize-1);
	$randElement=$array[$randKey];
}
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
array_rand() 3.46 ms Performance Graph 166%
code using rand() 2.08 ms Performance Graph 100%

Discussion: As the above results show, array_rand() is much slower than the code we made using rand(). It's not even close, and from my own experimentation (not shown here,) I have found that the gap widens as the number of elements increases. Lesson? Don't use array_rand().