Why doesn't rustc eliminate this empty loop?


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

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...


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


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.