Skip to content

Instantly share code, notes, and snippets.

@colinodell
Created May 30, 2016 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinodell/872c1f0c92351af687347c0c8be4f253 to your computer and use it in GitHub Desktop.
Save colinodell/872c1f0c92351af687347c0c8be4f253 to your computer and use it in GitHub Desktop.
array_change_keys() benchmark
<?php
$a = range(1, 10000000);
echo "Test 1 - Using foreach\n";
$start = microtime(true);
$b = [];
foreach ($a as $k => $v) {
$b[md5($v)] = $v;
}
echo "Time: " . (microtime(true) - $start)*1 . "\n";
echo "----------\n";
unset($b);
echo "Test 2 - Using existing methods\n";
$start = microtime(true);
$b = array_combine(
array_map(function ($value) {
return md5($value);
}, array_values($a)),
array_values($a)
);
echo "Time: " . (microtime(true) - $start)*1 . "\n";
echo "----------\n";
unset($b);
echo "Test 3 - Using array_change_keys\n";
$start = microtime(true);
$b = array_change_keys($a, function($k, $v) {
return md5($v);
});
echo "Time: " . (microtime(true) - $start)*1 . "\n";
echo "----------\n";
unset($b);

1. Download and compile PHP

git clone git@github.com:colinodell/php-src.git
cd php-src
git checkout -t origin/rfc/array-change-keys
./buildconf
./configure --prefix=/tmp/php7
make
make install

2. Run benchmark

/tmp/php7 -d memory_limit 4G /path/to/benchmark.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment