perf(optimizer): add sum range optimization #896
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
Currently sum ranges like
sum(1..100)andreduce(1..100, # + #acc)create a 100-element integer slice and iterate it element-by-element. When the range bounds are constant integers, this sum can be computed at compile time using the arithmetic series formula. This eliminates both the array allocation and iteration loop entirely.Changes
Add a new optimizer pass
sumRangethat detects these patterns:sum(m..n)sum(m..n, #): identity predicatesum(m..n, # * k)orsum(m..n, k * #): multiply each elementsum(m..n, # + k)orsum(m..n, k + #): add to each elementsum(m..n, # - k)orsum(m..n, k - #): subtract from each elementreduce(m..n, # + #acc)orreduce(m..n, #acc + #)reduce(m..n, # + #acc, initialValue): with optional initial valuePatterns are optimized with a constant
IntegerNodecontaining the result. The result is computed via the arithmetic series formula:(n - m + 1) * (m + n) / 2Benchmark run for
reduce:Benchstat showing a decent return:
cpu: Apple M1 Pro │ old.txt │ new.txt │ │ sec/op │ sec/op vs base │ _reduce-8 5182.00n ± 3% 27.82n ± 1% -99.46% (p=0.000 n=10) │ old.txt │ new.txt │ │ B/op │ B/op vs base │ _reduce-8 2448.00 ± 0% 32.00 ± 0% -98.69% (p=0.000 n=10) │ old.txt │ new.txt │ │ allocs/op │ allocs/op vs base │ _reduce-8 183.000 ± 0% 1.000 ± 0% -99.45% (p=0.000 n=10)Further comments
The optimization only applies when
n >= m. Reversed ranges likesum(10..1)are left unoptimized and handled by the runtime (returns 0 for sum, errors for reduce on empty array).