Skip to content

Instantly share code, notes, and snippets.

@morrisonlevi
Last active December 15, 2015 15:59
Show Gist options
  • Save morrisonlevi/5285627 to your computer and use it in GitHub Desktop.
Save morrisonlevi/5285627 to your computer and use it in GitHub Desktop.
Performance tests of implementing reduce in PHP.
<?php
function add($a, $b) {
return $a + $b;
}
function foldl(array $array, $function, $initial) {
if (empty($array)) {
return $initial;
}
$head = array_shift($array);
return call_user_func(__FUNCTION__, $array, $function, $function($initial, $head));
}
function foldLeft(array $array, $function, $initial) {
start:
if (empty($array)) {
return $initial;
}
$initial = $function($initial, array_shift($array));
goto start;
}
function foldr(array $array, $function, $initial) {
if (empty($array)) {
return $initial;
}
$head = array_pop($array);
return call_user_func(__FUNCTION__, $array, $function, $function($initial, $head));
}
function foldRight(array $array, $function, $initial) {
start:
if (empty($array)) {
return $initial;
}
$initial = $function($initial, array_pop($array));
goto start;
}
function reduce(array $array, $function, $initial) {
$carry = $initial;
foreach ($array as $item) {
$carry = $function($carry, $item);
}
return $carry;
}
$i = 0;
define('ITERATIONS', 100);
$data = range(1, 999);
$initial = 500;
$algorithms = array('foldl', 'foldLeft', 'foldr', 'foldRight', 'array_reduce', 'reduce');
foreach ($algorithms as $algorithm) {
$start = microtime(TRUE);
for ($i = 0; $i < ITERATIONS; $i++) {
call_user_func($algorithm, $data, 'add', $initial);
}
$stop = microtime(TRUE);
printf("Algorithm %s took %f seconds.\n", $algorithm, $stop - $start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment