captainhookphp / captainhook

CaptainHook is a very flexible git hook manager for software developers that makes sharing git hooks with your team a breeze.
http://captainhook.info
MIT License
996 stars 86 forks source link

Refactor array_merge out of loops #254

Closed kingkero closed 1 month ago

kingkero commented 1 month ago

I have read the CONTRIBUTING.md, as this does not introduce a new feature and touches very few points in general, I did decide against opening an issue first. I hope that is ok.

array_merge() inside loops is quite slow. Take a look at the following PHPBench example:

<?php

class ArrayMergeBench
{
  /**
   * @Revs(10000)
   * @Iterations(5)
   */
  public function benchMergeInLoop()
  {
    $result = [];

    for ($i=0; $i<100; $i++) {
      $result = array_merge($result, [$i]);
    }
  }

  /**
   * @Revs(10000)
   * @Iterations(5)
   */
  public function benchMergeOutsideLoop()
  {
    $result = [];

    for ($i=0; $i<100; $i++) {
      $result[] = [$i];
    }

    $finalResult = array_merge(...$result);
  }
}
returns benchmark subject set revs its mem_peak mode rstdev
ArrayMergeBench benchMergeInLoop 10000 5 2.808mb 23.545μs ±3.24%
ArrayMergeBench benchMergeOutsideLoop 10000 5 2.808mb 6.114μs ±4.93%

So even with a single element in the array, merging outside the loop is already 4x faster. The more elements in the loop, the slower merging inside will be.

sebastianfeldmann commented 1 month ago

Valid point :)