<?php
define('PREFIX', str_repeat('x', 1e1));
define('ITERATIONS', 1e4);
$data = array_fill(0, 1e1, str_repeat('y', 1e1));
if ($argc === 1) {
$funcs = array('array_walk', 'array_walk_cf', 'for', 'foreach', 'function_call');
shuffle($funcs);
foreach ($funcs as $func) {
$output = array();
exec('php -f ' . __FILE__ . ' ' . $func, $output);
echo implode("\n", $output) . "\n";
}
} elseif ($argv[1] === 'for') {
$start = microtime(true);
for ($i = 0; $i < ITERATIONS; $i++) {
$tmp = $data;
$c = count($tmp);
for ($j = 0; $j < $c; $j++) {
$tmp[$j] = PREFIX . $tmp[$j];
}
}
echo 'for: ' . (microtime(true) - $start) . ' - ' . md5(implode('', $tmp)) . "\n";
} elseif ($argv[1] === 'array_walk') {
$start = microtime(true);
$f = function (&$t) { $t = PREFIX . $t; };
for ($i = 0; $i < ITERATIONS; $i++) {
$tmp = $data;
array_walk($tmp, $f);
}
echo 'array_walk: ' . (microtime(true) - $start) . ' - ' . md5(implode('', $tmp)) . "\n";
} elseif ($argv[1] === 'array_walk_cf') {
$start = microtime(true);
$f = create_function('&$t', '$t = PREFIX . $t;');
for ($i = 0; $i < ITERATIONS; $i++) {
$tmp = $data;
array_walk($tmp, $f);
}
echo 'array_walk_cf: ' . (microtime(true) - $start) . ' - ' . md5(implode('', $tmp)) . "\n";
} elseif ($argv[1] === 'foreach') {
$start = microtime(true);
for ($i = 0; $i < ITERATIONS; $i++) {
$tmp = $data;
foreach ($tmp as &$t) {
$t = PREFIX . $t;
}
unset($t);
}
echo 'foreach: ' . (microtime(true) - $start) . ' - ' . md5(implode('', $tmp)) . "\n";
} elseif ($argv[1] === 'function_call') {
function f(&$t)
{
$t = PREFIX . $t;
}
$start = microtime(true);
for ($i = 0; $i < ITERATIONS; $i++) {
$tmp = $data;
$c = count($tmp);
for ($j = 0; $j < $c; $j++) {
f($tmp[$j]);
}
}
echo 'function_call: ' . (microtime(true) - $start) . ' - ' . md5(implode('', $tmp)) . "\n";
}