3v4l.org

run code in 300+ PHP versions simultaneously
<?php $testList = [ [ 'array' => [], 'expect' => true, ], [ 'array' => ['a', 'b', 'c'], 'expect' => true, ], [ 'array' => ["0" => 'a', "1" => 'b', "2" => 'c'], 'expect' => true, ], [ 'array' => ["1" => 'a', "0" => 'b', "2" => 'c'], 'expect' => false, ], [ 'array' => ["a" => 'a', "b" => 'b', "c" => 'c'], 'expect' => false, ], ]; function displayBenchmark($function) { global $testList; echo '<h5>use function <code>' . $function . '</code></h5>'; $i = 0; $startTime = microtime(true); for ($i = 0; $i <= 1000; ++$i) { foreach ($testList as $testItem) { $result = $function($testItem['array']); assert($result === $testItem['expect'], 'Unexpect matched on index ' . $i); ++$i; } } $totalTime = microtime(true) - $startTime; echo 'total time: ' . var_export($totalTime, true) . '<br>'; } function array_is_list1(array $arr) { if ($arr === []) { return true; } return array_keys($arr) === range(0, count($arr) - 1); } function array_is_list2(array $array): bool { $i = -1; foreach ($array as $k => $v) { ++$i; if ($k !== $i) { return false; } } return true; } class Benchmark { private static $max, $memory; public static function memoryTick() { self::$memory = memory_get_usage() - self::$memory; self::$max = self::$memory>self::$max?self::$memory:self::$max; self::$memory = memory_get_usage(); } public static function benchmarkMemory(callable $function, $args=null) { declare(ticks=1); self::$memory = memory_get_usage(); self::$max = 0; register_tick_function('call_user_func_array', ['Benchmark', 'memoryTick'], []); $result = is_array($args)? call_user_func_array($function, $args): call_user_func($function); unregister_tick_function('call_user_func_array'); return [ 'memory' => self::$max ]; } } var_dump(Benchmark::benchmarkMemory('displayBenchmark', ['array_is_list'])); var_dump(Benchmark::benchmarkMemory('displayBenchmark', ['array_is_list1'])); var_dump(Benchmark::benchmarkMemory('displayBenchmark', ['array_is_list2']));

preferences:
24.33 ms | 413 KiB | 5 Q