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 Enumerable#sum for integer ranges #2359

Merged
merged 1 commit into from
Nov 26, 2024

Conversation

herwinw
Copy link
Member

@herwinw herwinw commented Nov 25, 2024

We can simply shortcut this with the Guass formula for summing integers. It turns out MRI does this too

Benchmarking this with (1..1000000).sum, this takes roughly 1.5 seconds on master (on my machine, release build), and only 0.00003 seconds with this patch. MRI is still roughly 10 times as fast.

Inspired by https://mastodon.social/@riffraff/113503953295615142, mentioned on https://newsletter.shortruby.com/p/edition-115
MRI does not have a separate Range#sum method, so it looks like it is shortcutted in Enumerable#range.

We can simply shortcut this with the Guass formula for summing integers.
It turns out MRI does this too

Benchmarking this with `(1..1000000).sum`, this takes roughly 1.5
seconds on master (on my machine, release build), and only 0.00003
seconds with this patch. MRI is still roughly 10 times as fast.

Inspired by https://mastodon.social/@riffraff/113503953295615142,
mentioned on https://newsletter.shortruby.com/p/edition-115
MRI does not have a separate `Range#sum` method, so it looks like it is
shortcutted in `Enumerable#range`.
@herwinw herwinw merged commit 93e4dff into natalie-lang:master Nov 26, 2024
15 checks passed
@herwinw herwinw deleted the range_sum branch November 26, 2024 06:55
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