Skip to content

Instantly share code, notes, and snippets.

@amalmurali47
Created February 25, 2014 17:11
Show Gist options
  • Save amalmurali47/9213340 to your computer and use it in GitHub Desktop.
Save amalmurali47/9213340 to your computer and use it in GitHub Desktop.
array_rand() vs shuffle() - Benchmark
<pre><?php
$arr = array(
array(
"image" => "",
"title" => "Open 7 days.",
"text" => "We’re open 7 days a week."
),
array(
"image" => "",
"title" => "Well done",
"text" => "Well done you done great."
),
array(
"image" => "",
"title" => "Rice",
"text" => "Various flavours"
),
array(
"image" => "",
"title" => "Rooms",
"text" => "Roomy rooms for a roomyful time"
),
array(
"image" => "",
"title" => "Keep in touch.",
"text" => "Stay in touchwith us as we'll miss you"
),
array(
"image" => "",
"title" => "Location",
"text" => "We'll show you where we are."
),
array(
"image" => "",
"title" => "The Home",
"text" => "See our home page"
)
);
for ($i=0; $i < 11; $i++) {
$arr = array_merge($arr, $arr);
}
printf("Our array contains %s elements\n", count($arr));
// V1
$start = microtime(1);
for ($i=0; $i < 10000; $i++) {
$result = array();
foreach (array_rand($arr, 4) as $k) {
$result[] = $arr[$k];
}
}
$end = microtime(1);
printf('V1 took %ss', round($end-$start, 3));
echo "\n";
// V2
$start = microtime(1);
for ($i=0; $i < 10000; $i++) {
$result = array();
shuffle($arr);
$result = array_slice($arr,0,4);
}
$end = microtime(1);
printf('V2 took %ss', round($end-$start, 3));
/*
Results on my dev server:
Our array contains 14336 elements
V1 took 4.659s
V2 took 15.071s
*/
@friedrichroell
Copy link

friedrichroell commented Apr 12, 2018

cheers!
Our array contains 14336 elements V1 took 0.416s V2 took 4.934s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment