Why doesn't rustc eliminate this empty loop?

https://rust.godbolt.org/z/rY95oGMYd

pub fn test(){
    for _ in 0..=1024 {}
}
4 Likes

Interestingly, it does eliminate this loop:

pub fn test(){
    for _ in 0..1024 {}
}

That's so weird. It doesn't even loop 1024 times. Does the compiler think we are gonna use the value of eax?

There are quite a few known performance problems with inclusive ranges...
https://github.com/rust-lang/rust/issues/45222

3 Likes

Interestingly this loop was optimized out in 1.42.0, regressed to horrible code generation in 1.43.0 and recovered a bit to the current non-optimal state of affairs in 1.47.0 - Godbolt.

1 Like

This is just the extreme case of "you should use internal iteration for cheap loop bodies". If you

(0..=1024).for_each(|_| {})

then it optimizes out just fine, even at only opt-level 1: https://rust.godbolt.org/z/oP8TEhadr

More in previous threads like

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.