PHP & Web Development :: PHP Performance + Benchmarking :: Rand Array Element Access

Random Array Element Access: rand() vs. array_rand()

BulletOften 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 4.3.11 with PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's Zend Optimizer?

Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable.

Refresh the page to execute a new trial!

Comparisons
Bulletarray_rand()
  • Execution time: 4.66 ms
  • Average: 3.03 ms over 943 trials
Bulletcode using rand()
  • Execution time: 1.81 ms
  • Average: 2.05 ms over 943 trials
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
array_rand() 3.03 ms Performance Graph 148%
code using rand() 2.05 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().