normalizeSku($sku), $items); } function foreachCall(array $items): array { $result = []; foreach ($items as $key => $sku) { $result[$key] = normalizeSku($sku); } return $result; } function foreachInline(array $items): array { $result = []; foreach ($items as $key => $sku) { $result[$key] = strtoupper(trim($sku)); } return $result; } $mode = $argv[1] ?? 'all'; $iterations = filter_var($argv[2] ?? '3000', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000000]]); $size = filter_var($argv[3] ?? '200', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100000]]); $tasks = [ 'map-first-class' => mapFirstClass(...), 'map-closure' => mapClosure(...), 'foreach-call' => foreachCall(...), 'foreach-inline' => foreachInline(...), ]; if (false === $iterations || false === $size || ('all' !== $mode && !isset($tasks[$mode]))) { fwrite(STDERR, "Usage: php benchmark.php [all|map-first-class|map-closure|foreach-call|foreach-inline] [iterations:1..1000000] [size:1..100000]\n"); exit(1); } $items = []; for ($i = 0; $i < $size; ++$i) { $items['product-'.$i] = ' sku-'.$i.' '; } $expected = foreachInline($items); foreach ($tasks as $name => $task) { if ($task($items) !== $expected) { throw new RuntimeException('Different output or keys: '.$name); } } if ('all' !== $mode) { $tasks = [$mode => $tasks[$mode]]; } printf("PHP %s | %s | OPcache CLI=%s | JIT=%s | JIT buffer=%s\n", PHP_VERSION, PHP_OS_FAMILY, ini_get('opcache.enable_cli'), ini_get('opcache.jit'), ini_get('opcache.jit_buffer_size')); printf("Iterations=%d | Elements=%d | Samples=7 | Result equality: OK\n", $iterations, $size); // Warm every variant before collecting seven samples in randomized order. foreach ($tasks as $task) { for ($i = 0; $i < 200; ++$i) { $task($items); } } $samples = array_fill_keys(array_keys($tasks), []); $checksum = 0; for ($round = 0; $round < 7; ++$round) { $order = array_keys($tasks); shuffle($order); foreach ($order as $name) { $task = $tasks[$name]; $start = hrtime(true); for ($i = 0; $i < $iterations; ++$i) { $result = $task($items); $checksum += count($result); } $samples[$name][] = (hrtime(true) - $start) / 1e6; } } foreach ($samples as $name => $times) { sort($times); printf("%-18s median=%9.3f ms | min=%9.3f | max=%9.3f\n", $name, $times[3], $times[0], $times[6]); } printf("Checksum=%d\n", $checksum);