Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.