- This topic has 2 replies, 1 voice, and was last updated 2 months, 1 week ago by MicrowaveLover.
- AuthorPosts
- November 8, 2020 at 12:47 pm #1814pepelkoParticipant
I made this test today, but I’m not able to explain it myself (the last, slowest case). I’m hoping someone here does.
PHP version is 7.4.11, with opcache enabled (the results below are after multiple runs).
$ php array_push_bench.php
Running tests 20 times.
Testing 6/6 : array_push + spread + generatorTest Time Time (%) Memory Memory (%)
[] + foreach 1042 ms 0 B
array_push + spread 1137 ms 9 % 0 B
[] + foreach + generator 1191 ms 14 % 0 B
array_push + foreach 1254 ms 20 % 0 B
array_push + foreach + generator 1448 ms 39 % 0 B
array_push + spread + generator 11044 ms 960 % 0 BThe code:
<?php
// “lavoiesl/php-benchmark”: “^1.4”,
use LavoieslPhpBenchmarkBenchmark;require_once __DIR__ . ‘/vendor/autoload.php’;
const DEFAULT_COUNT = 1000000;
function xrange(int $count = DEFAULT_COUNT): Generator
{
for ($i = 0; $i < $count; $i++) {
yield $i;
}
}function nrange(int $count = DEFAULT_COUNT): array
{
return range(0, $count);
}$bench = new Benchmark();
$bench->add(
‘[] + foreach’,
function () {
$array = [];
foreach (nrange() as $i) {
$array[] = $i;
}
}
);$bench->add(
‘array_push + foreach’,
function () {
$array = [];
foreach (nrange() as $i) {
array_push($array, $i);
}
}
);$bench->add(
‘array_push + spread’,
function () {
$array = [];
array_push($array, …nrange());
}
);$bench->add(
‘[] + foreach + generator’,
function () {
$array = [];
foreach (xrange() as $i) {
$array[] = $i;
}
}
);$bench->add(
‘array_push + foreach + generator’,
function () {
$array = [];
foreach (xrange() as $i) {
array_push($array, $i);
}
}
);$bench->add(
‘array_push + spread + generator’,
function () {
$array = [];
array_push($array, …xrange());
}
);$bench->guessCount(10);
$bench->run();November 8, 2020 at 12:47 pm #1815MUK99GuestWhat the fuck am I looking at
November 8, 2020 at 12:47 pm #1816MicrowaveLoverGuestFirst thing is that 10 or 20 runs is definitely not enough.
Second is that you made it so xrange with no arguments ends after a million calls, so probably in last case it’s unpacked at once and copied over a few times, which is really slow for million elements.Other than that I have no guesses.
- AuthorPosts
- You must be logged in to reply to this topic.