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

[11.x] Collection average/avg optimization #51512

Merged
merged 3 commits into from
May 20, 2024

Conversation

bert-w
Copy link
Contributor

@bert-w bert-w commented May 20, 2024

This PR includes an algorithm improvement for the Collection avg() and average() function.

The previous code used an inefficient map+filter+count, whereas the new implementation does it all at once with a reducer.

Algo explanation

  1. Start with a reducer array with 2 empty elements [0, 0]
  2. Loop/reduce the array:
    • add (sum) all non-null values to the first array element
    • increment the second array element with 1 (the count)
  3. After loop: $avg = $reduced[0] / $reduced[1]

Additionally, the function has been moved to the EnumeratesValues trait so the lazy collection can also benefit from this optimization. It also works as expected with yield.

Benchmark (gist)

Size Old (ms) New (ms) % Improvement
10 0.0707 0.0614 13.14%
100 0.3149 0.221 29.78%
1,000 3.1159 2.2254 28.57%
10,000 31.0282 23.3528 24.71%
100,000 315.3512 232.7599 26.22%
1,000,000 3,219.9169 2,151.9144 33.17%

Copy link

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@bert-w bert-w marked this pull request as ready for review May 20, 2024 12:26
@taylorotwell taylorotwell merged commit 3b70842 into laravel:11.x May 20, 2024
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants