Skip to content

Instantly share code, notes, and snippets.

@stekycz
Last active December 27, 2015 09:19
Show Gist options
  • Save stekycz/7303167 to your computer and use it in GitHub Desktop.
Save stekycz/7303167 to your computer and use it in GitHub Desktop.
Simple benchmark of PHP build-in functions for arrays and general foreach.
<?php
ini_set('memory_limit', '4G');
$last_time = microtime(TRUE);
function timer() {
global $last_time;
$previous = $last_time;
$last_time = microtime(TRUE);
return $last_time - $previous;
}
function generate_array($size) {
$array = array();
for ($i = 0; $i < $size; $i++) {
$array[] = $i;
}
return $array;
}
function test_array_filter($array) {
$filter = function ($i) {
return $i % 2 == 0;
};
timer();
$filtered = array_filter($array, $filter);
echo timer() . "\n";
timer();
$filtered = array();
foreach ($array as $i) {
if ($filter($i)) {
$filtered[] = $i;
}
}
echo timer() . "\n";
timer();
$filtered = array();
foreach ($array as $i) {
if ($i % 2 == 0) {
$filtered[] = $i;
}
}
echo timer() . "\n";
}
function test_array_reduce($array) {
$reduce = function ($sum, $i) {
return $sum + $i;
};
timer();
$sum = array_reduce($array, $reduce, 0);
echo timer() . "\n";
timer();
$sum = 0;
foreach ($array as $i) {
$sum = $reduce($sum, $i);
}
echo timer() . "\n";
timer();
$sum = 0;
foreach ($array as $i) {
$sum = $sum + $i;
}
echo timer() . "\n";
timer();
$sum = array_sum($array);
echo timer() . "\n";
}
function test_array_map($array) {
$mapper = function ($num) {
return $num + 1;
};
timer();
array_walk($array, $mapper);
echo timer() . "\n";
timer();
foreach ($array as $key => $i) {
$array[$key] = $mapper($i);
}
echo timer() . "\n";
timer();
foreach ($array as $key => $i) {
$array[$key] = $i + 1;
}
echo timer() . "\n";
}
function test_array_walk($array) {
timer();
array_walk($array, function () {});
echo timer() . "\n";
timer();
foreach ($array as $i) {}
echo timer() . "\n";
}
// $array_sizes = array(10, 50, 100, 200, 500, 1000);
$array_sizes = array(1000, 5000, 10000, 50000, 100000, 500000, 1000000);
foreach ($array_sizes as $size) {
echo $size . "\n";
$array = generate_array($size);
echo "array_filter\n";
test_array_filter($array);
echo "array_reduce\n";
test_array_reduce($array);
echo "array_map\n";
test_array_map($array);
echo "array_walk\n";
test_array_walk($array);
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment