Array append benchmark

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #1814
    pepelko
    Participant

    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 + generator

    Test 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 B

    The 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();

    #1815
    MUK99
    Guest

    What the fuck am I looking at

    #1816
    MicrowaveLover
    Guest

    First 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.

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.