Range optimizations opportunities

Viewed 87

Those two functions have the same behavior, however compiler optimizes those differently.

pub fn sum_positive_1(n: i32) -> i32 {
    let mut acc = 0;

    for i in 1..=n {
        acc += i
    }

    acc
}
pub fn sum_positive_2(n: i32) -> i32 {
    let mut acc = 0;

    for i in 1..n + 1 {
        acc += i
    }

    acc
}

Assembly produced.


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_1 has O(N) complexity.
  • sum_positive_2 has O(1) complexity, because the closed-form is used.

Indeed, simple benchmark on my machine:

  • sum_positive_1(1048576) -> execution 2.1158 ms
  • sum_positive_2(1048576) -> execution 3.4063 ns

Why RangeInclusive inhibits this kind of optimization?

0 Answers
Related