3

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?

BiagioF
  • 9,368
  • 2
  • 26
  • 50
  • [This is also a worth of read](https://stackoverflow.com/a/70514035/6699447) but it's not a duplicate. – Abdul Niyas P M Jan 31 '22 at 17:59
  • 1
    Does this answer your question? [Why does iteration over an inclusive range generate longer assembly in Rust?](https://stackoverflow.com/questions/70672533/why-does-iteration-over-an-inclusive-range-generate-longer-assembly-in-rust) (Oh, I could have just voted earlier; didn't realize this was missing any tags I had a gold badge in.) – Peter Cordes Jan 31 '22 at 18:13
  • No, it doesn’t, actually. – user3840170 Apr 26 '23 at 05:49

0 Answers0