Skip to content

Instantly share code, notes, and snippets.

@Dimasmagadan
Last active May 1, 2025 10:13
Show Gist options
  • Save Dimasmagadan/b615a1b79277af4cff3a850b78c6395a to your computer and use it in GitHub Desktop.
Save Dimasmagadan/b615a1b79277af4cff3a850b78c6395a to your computer and use it in GitHub Desktop.
<?php
function benchmark(string $label, callable $callback): void {
$start = microtime(true);
$callback();
$end = microtime(true);
$duration = $end - $start;
echo str_pad($label, 35) . ': ' . number_format($duration * 1000, 4) . " ms\n";
}
$array = range(1, 2000000); // adjust for load
$len = count($array);
// foreach / 2
benchmark('foreach / 2', function () use ($array) {
$result = [];
foreach ($array as $v) {
$result[] = $v / 2;
}
});
// array_map with / 2
benchmark('array_map / 2', function () use ($array) {
$result = array_map(fn($v) => $v / 2, $array);
});
// for with / 2 (count inside loop)
benchmark('for / 2 (inline count)', function () use ($array) {
$result = [];
for ($i = 0; $i < count($array); $i++) {
$result[] = $array[$i] / 2;
}
});
// for with / 2 (cached count)
benchmark('for / 2 (cached count)', function () use ($array, $len) {
$result = [];
for ($i = 0; $i < $len; $i++) {
$result[] = $array[$i] / 2;
}
});
// foreach / 2 + range check
benchmark('foreach / 2 + range check', function () use ($array) {
$result = [];
foreach ($array as $v) {
if ( $v <= 2000000 ) {
$result[] = $v / 2;
}
}
});
// foreach * 0.5
benchmark('foreach * 0.5', function () use ($array) {
$result = [];
foreach ($array as $v) {
$result[] = $v * 0.5;
}
});
// array_map with * 0.5
benchmark('array_map * 0.5', function () use ($array) {
$result = array_map(fn($v) => $v * 0.5, $array);
});
// for with * 0.5 (cached count)
benchmark('for * 0.5 (cached count)', function () use ($array, $len) {
$result = [];
for ($i = 0; $i < $len; $i++) {
$result[] = $array[$i] * 0.5;
}
});
// foreach * 0.5 + range check
benchmark('foreach * 0.5 + range check', function () use ($array) {
$result = [];
foreach ($array as $v) {
if ( $v <= 2000000 ) {
$result[] = $v * 0.5;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment