<?php
function returnTime(callable $function)
{
$count = 100;
$repeat = 100;
$tests = [];
for ($i = 0; $i < $repeat; $i++) {
$tests[$i] = [];
for ($i = 0; $i < $count; $i++) {
$startTime = microtime(true);
$function();
$endTime = microtime(true);
$tests[$i][] = $endTime - $startTime;
}
}
foreach ($tests as &$test)
$test = array_sum($test);
return array_sum($tests) / $repeat;
}
function compareResults($result1, $name1, $result2, $name2) {
$results = [
$result1,
$result2,
];
$names = [
$name1,
$name2,
];
if ($results[0] == $results[1]) {
return 0;
}
if ($results[0] < $results[1]) {
$fasterIndex = 0;
} else {
$fasterIndex = 1;
}
$slowerIndex = 1 - $fasterIndex;
$fasterResult = $results[$fasterIndex];
$slowerResult = $results[$slowerIndex];
echo "{$names[$fasterIndex]} performs faster than {$names[$slowerIndex]}.", PHP_EOL;
echo "It is ", round(($slowerResult / $fasterResult) * 100 - 100), "% faster.", PHP_EOL;
}
// Array with 500000 elements
$array = array_fill(0, 500000, 1);
compareResults(
returnTime(function () use ($array) {
end($array);
$lastKey = key($array);
reset($array);
}),
"end()",
returnTime(function () use ($array) {
$lastKey = key(array_slice($array, -1, 1, true));
}),
"array_slice()"
);
Abusive script
This script was stopped while abusing our resources
preferences:
28.25 ms | 411 KiB | 5 Q