Last active
December 17, 2023 12:10
-
-
Save macocci7/eee86e1c5b6982edbe578dd3f38f3714 to your computer and use it in GitHub Desktop.
Script to benchmark the performance of adding array elements (配列要素追加処理のベンチマークスクリプト)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function benchmark(string $name, Closure $callback) | |
{ | |
$start = microtime(true); | |
$callback(); | |
$time = microtime(true) - $start; | |
echo sprintf( | |
"%24s =>\tTime: %.6f sec.\n", | |
$name, | |
$time | |
); | |
} | |
$iteration = 10000; | |
// array_push() | |
benchmark( | |
'array_push()', | |
function () use ($iteration) { | |
$a = []; | |
for ($i = 0; $i < $iteration; $i++) { | |
array_push($a, 1); | |
} | |
} | |
); | |
// square brackets | |
benchmark( | |
'square brackets []', | |
function () use ($iteration) { | |
$a = []; | |
for ($i = 0; $i < $iteration; $i++) { | |
$a[] = 1; | |
} | |
} | |
); | |
// union operator | |
benchmark( | |
'union operator +=', | |
function () use ($iteration) { | |
$a = []; | |
for ($i = 0; $i < $iteration; $i++) { | |
$a += [count($a) => 1]; | |
} | |
} | |
); | |
// array_merge() | |
benchmark( | |
'array_merge()', | |
function () use ($iteration) { | |
$a = []; | |
for ($i = 0; $i < $iteration; $i++) { | |
$a = array_merge($a, [1]); | |
} | |
} | |
); | |
// unpacking operator | |
benchmark( | |
'unpacking operator [...]', | |
function () use ($iteration) { | |
$a = []; | |
for ($i = 0; $i < $iteration; $i++) { | |
$a = [...$a, 1]; | |
} | |
} | |
); | |
// ArrayObject | |
benchmark( | |
'ArrayObject', | |
function () use ($iteration) { | |
$a = new ArrayObject([]); | |
for ($i = 0; $i < $iteration; $i++) { | |
$a->append(1); | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result of running 5 times:
1st:
2nd:
3rd:
4th:
5th: