Skip to content

Instantly share code, notes, and snippets.

@tanakahisateru
Last active May 25, 2016 13:55
Show Gist options
  • Select an option

  • Save tanakahisateru/c026e04e4107886b3842854612df539e to your computer and use it in GitHub Desktop.

Select an option

Save tanakahisateru/c026e04e4107886b3842854612df539e to your computer and use it in GitHub Desktop.
PHP array operation speed test
<?php
require __DIR__ . '/vendor/autoload.php';
$size = 1000000;
$repeat = max([1, intval(5000000 / $size)]);
$targetArray = range(1, $size);
function plus1($n) {
return $n + 1;
}
/////////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = Ginq::from($targetArray)->select(function($n) { return $n + 1; })->toList();
}
$t = microtime(true) - $s;
printf("Ginq + Closure: %0.4fms x1.00\n", $t * 1000 / $repeat);
$base = $t;
///////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = Ginq::from($targetArray)->select('plus1')->toList();
}
$t = microtime(true) - $s;
printf("Ginq + function: %0.4fms x%0.2f\n", $t * 1000 / $repeat, $base / $t);
/////////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = array_map(function($n){ return $n + 1; }, $targetArray);
}
$t = microtime(true) - $s;
printf("array_map + Closure: %0.4fms x%0.2f\n", $t * 1000 / $repeat, $base / $t);
/////////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = array_map('plus1', $targetArray);
}
$t = microtime(true) - $s;
printf("array_map + function: %0.4fms x%0.2f\n", $t * 1000 / $repeat, $base / $t);
/////////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = [];
foreach ($targetArray as $k => $v) {
$buf[$k] = $v + 1;
}
}
$t = microtime(true) - $s;
printf("foreach with key: %0.4fms x%0.2f\n", $t * 1000 / $repeat, $base / $t);
/////////////////////////////////////////////////
sleep(1);
$s = microtime(true);
for ($i=0; $i < $repeat; $i++) {
$buf = [];
foreach ($targetArray as $v) {
$buf[] = $v + 1;
}
}
$t = microtime(true) - $s;
printf("foreach without key: %0.4fms x%0.2f\n", $t * 1000 / $repeat, $base / $t);
/*
> php -d memory_limit=-1 array-spped-test.php
Ginq + Closure: 782.2070ms x1.00
Ginq + function: 785.6706ms x1.00
array_map + Closure: 99.5564ms x7.86
array_map + function: 67.2468ms x11.63
foreach with key: 52.4326ms x14.92
foreach without key: 46.9100ms x16.67
*/
{
"require": {
"ginq/ginq": "^0.2.4"
}
}
> php -d memory_limit=-1 array-spped-test.php
Ginq + Closure: 782.2070ms x1.00
Ginq + function: 785.6706ms x1.00
array_map + Closure: 99.5564ms x7.86
array_map + function: 67.2468ms x11.63
foreach with key: 52.4326ms x14.92
foreach without key: 46.9100ms x16.67
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment