Steve's weblog


Extracting random elements from an array with php  

Cat.: General stuff
08. July 2011

Steve Frost (@stevefrost) asked about the speed difference between two different code approaches in php to extract 10 random elements from an array.

Being a bit of a number cruncher, this felt like a nice challenge. So I wrote a ruby class (so much nicer than php :-) ) to take a command line script and run it 25 times and record how long each run took. This gave me the ability to gather one sample so this was wrapped with a script that ran the two different code snippets with increasing array sizes and voila;
Relative performance of shuffle vs random

This clearly shows that the use of shuffle is much slower as the size of the array increases – indeed it would appear to be an exponential curve as opposed to a linear relationship.

I should look at adding in some statistical tests to my test harness – but that will be another day!

Leave a Reply

You must be logged in to post a comment.