Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor array_merge out of loops #254

Merged
merged 1 commit into from
Aug 30, 2024

Conversation

kingkero
Copy link
Contributor

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
Copy link
Collaborator

Valid point :)

Copy link
Collaborator

@sebastianfeldmann sebastianfeldmann left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great!
Thanks

@sebastianfeldmann sebastianfeldmann merged commit 454d537 into captainhookphp:main Aug 30, 2024
4 checks passed
@kingkero kingkero deleted the faster-array-merge branch August 30, 2024 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants