<?php function benchmark(callable ...$functions): void { $times = array_combine(array_keys($functions), array_fill(0, count($functions), 0.0)); $baseTime = 0.0; $baseCallable = fn() => null; $start = hrtime(true); $count = 0; while (hrtime(true) < $start + 1e9) { $startCall = hrtime(true); $baseCallable(); $baseTime += hrtime(true) - $startCall; foreach ($functions as $key => $function) { $startCall = hrtime(true); $function(); $times[$key] += hrtime(true) - $startCall; } $count++; } foreach ($times as $key => $time) { $times[$key] = $time - $baseTime; } if ($count < 100) { echo "Methods too low. Iterated only {$count} times\n"; } asort($times); echo "Benchmark results after {$count} iterations in nanoseconds:\n"; foreach ($times as $key => $time) { echo $key . ': ' . $time . "\n"; } } enum OptionEnum: string { case Option1 = 'opt1'; case Option2 = 'opt2'; case Option3 = 'opt3'; case Option4 = 'opt4'; case Option5 = 'opt5'; public static function values(): array { return ['opt1', 'opt2', 'opt3', 'opt4', 'opt5']; } public static function valuesArrayMap(): array { return array_map(static fn(self $c) => $c->value, self::cases()); } public static function valuesArrayColumn(): array { return array_column(self::cases(), 'value'); } } benchmark( arrayRaw: fn() => OptionEnum::values(), arrayMap: fn() => OptionEnum::valuesArrayMap(), arrayCol: fn() => OptionEnum::valuesArrayColumn(), );
You have javascript disabled. You will not be able to edit any code.