Those two functions have the same behavior, however compiler optimizes those differently.
- With RangeInclusive:
pub fn sum_positive_1(n: i32) -> i32 {
let mut acc = 0;
for i in 1..=n {
acc += i
}
acc
}
- With Range
pub fn sum_positive_2(n: i32) -> i32 {
let mut acc = 0;
for i in 1..n + 1 {
acc += i
}
acc
}
As you can see in the assembly, the compiler optimizes the loop in sum_positive_2. However, it does not in sum_positive_1.
sum_positive_1has O(N) complexity.sum_positive_2has O(1) complexity, because the closed-form is used.
Indeed, simple benchmark on my machine:
sum_positive_1(1048576)-> execution2.1158 mssum_positive_2(1048576)-> execution3.4063 ns
Why RangeInclusive inhibits this kind of optimization?