- var_dump: documentation ( source)
- abs: documentation ( source)
- microtime: documentation ( source)
- str_repeat: documentation ( source)
- str_split: documentation ( source)
#!/usr/bin/php
<?php
declare(strict_types=1);
const ITERATIONS = 100000;
$results = array();
for ($i = 0; $i < ITERATIONS; ++$i) {
// heat up cpu (if it was powersaving-running-low-cus-nothing-was-happening, most modern cpus try to do it by default)
}
function array_is_list_post(array $array): bool
{
$i = 0;
foreach ($array as $k => $v) {
if ($k !== $i++) {
return false;
}
}
return true;
}
function array_is_list_pre(array $array): bool
{
$i = -1;
foreach ($array as $k => $v) {
++$i;
if ($k !== $i) {
return false;
}
}
return true;
}
$l1 = str_split(str_repeat("A", 300), 1);
$t = microtime(true);
for ($i = 0; $i < ITERATIONS; ++$i) {
array_is_list_pre($l1);
}
$t = microtime(true) - $t;
$results["pre"] = $t;
$t = microtime(true);
for ($i = 0; $i < ITERATIONS; ++$i) {
array_is_list_post($l1);
}
$t = microtime(true) - $t;
$results["post"] = $t;
if ($results["pre"] === $results["post"]) {
echo "it's a tie!";
} elseif ($results["pre"] < $results["post"]) {
echo "pre is faster!";
} else {
echo "post is faster!";
}
echo "diff: " . abs(($results["pre"] - $results["post"])) . "\n";
var_dump($results);
exit();