Skip to content

Instantly share code, notes, and snippets.

@kalimatas
Last active May 26, 2020 13:02
Show Gist options
  • Save kalimatas/6e8d3d455443922820074396329cfadb to your computer and use it in GitHub Desktop.
Save kalimatas/6e8d3d455443922820074396329cfadb to your computer and use it in GitHub Desktop.
PHPBench array_push vs array_merge
<?php
declare(strict_types = 1);
use PhpBench\Benchmark\Metadata\Annotations\BeforeMethods;
use PhpBench\Benchmark\Metadata\Annotations\Revs;
require 'vendor/autoload.php';
/**
* @BeforeMethods({"prepare"})
*/
class PushVsMergeBench
{
private $a = [];
private $b = [];
public function prepare()
{
$this->a = [];
$this->b = [];
for ($i = 0; $i < 100000; $i++) {
$this->a[] = new \stdClass();
$this->b[] = new \stdClass();
}
}
/**
* @Revs(100)
*/
public function benchArrayMerge()
{
$this->a = array_merge($this->a, $this->b);
}
/**
* @Revs(100)
*/
public function benchArrayPush()
{
array_push($this->a, ...$this->b);
}
}
@mente
Copy link

mente commented Dec 13, 2016

Generation of data is included in benchmarking which might dillute actual results. Chock http://phpbench.readthedocs.io/en/latest/writing-benchmarks.html#subject-runtime-state-before-and-after

@kalimatas
Copy link
Author

Updated to have @BeforeMethods({"prepare"}). Now the results are pretty different:

+------------------+-----------------+--------+--------+------+------+----------------+---------------+--------------+----------------+
| benchmark        | subject         | groups | params | revs | iter | mem_peak       | time_rev      | comp_z_value | comp_deviation |
+------------------+-----------------+--------+--------+------+------+----------------+---------------+--------------+----------------+
| PushVsMergeBench | benchArrayMerge |        | []     | 100  | 0    | 1,088,799,600b | 259,224.550μs | 0.00σ        | 0.00%          |
| PushVsMergeBench | benchArrayPush  |        | []     | 100  | 0    | 553,759,544b   | 7,336.010μs   | 0.00σ        | 0.00%          |
+------------------+-----------------+--------+--------+------+------+----------------+---------------+--------------+----------------+

@mente
Copy link

mente commented Dec 13, 2016

It was php 7.0 right?

I told you :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment