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

Optimize Money#split(n) for large n #287

Merged
merged 1 commit into from
Apr 11, 2024
Merged

Optimize Money#split(n) for large n #287

merged 1 commit into from
Apr 11, 2024

Conversation

casperisfine
Copy link
Contributor

When passing a very large number to split, it result in allocating between 2 and 3 arrays of such size. e..g Money.new(1_000_000).split(1_000_000) allocates an array of size 1M, then concat it with an empty array, which cause Ruby to allocate another array of 1M entries.

All this cause two 8MB mallocs, which doesn't sound like that much but if done a few times is likely to trigger Ruby GC.

Instead we can return a small enumerable that will simply act like an array, but won't actually materialize it.

lib/money/money.rb Outdated Show resolved Hide resolved
lib/money/money.rb Outdated Show resolved Hide resolved
lib/money/splitter.rb Outdated Show resolved Hide resolved
When passing a very large number to split, it result in allocating
between 2 and 3 arrays of such size. e..g `Money.new(1_000_000).split(1_000_000)`
allocates an array of size 1M, then concat it with an empty array, which cause
Ruby to allocate another array of 1M entries.

All this cause two `8MB` mallocs, which doesn't sound like that much
but if done a few times is likely to trigger Ruby GC.

Instead we can return a small enumerable that will simply act like an
array, but won't actually materialize it.
@casperisfine casperisfine merged commit d2b1523 into main Apr 11, 2024
9 checks passed
@casperisfine casperisfine deleted the split-allocations branch April 11, 2024 06:44
@elfassy elfassy mentioned this pull request Apr 17, 2024
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.

None yet

3 participants