3

Aside from the fact that it can reason about uninitialized values set within the loop body, are there any other compelling reasons for loop to exist ?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
sa___
  • 343
  • 2
  • 12

1 Answers1

1

Other than you state your intention, there is no difference. All loops are the same once normalization has happened in the compiler.

See an example of a loop in the Rust playground and the same example with a while true. The assembly generated is exactly the same. The compiler gives a warning for the while true-example to use loop instead.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
user2722968
  • 10,969
  • 2
  • 32
  • 55
  • Can you prove this in any way? – Shepmaster Jun 04 '17 at 00:00
  • @Shepmaster you could compare MIR or ASM output if proof is required – the8472 Jun 04 '17 at 06:42
  • @the8472 that only proves that the assembly (and presumably relevant optimizations) is the same *for a single case*, which is a pretty low bar. I could imagine wildly different code samples that compile to the same assembly even though the path to get to get there is completely different (thus having different available optimizations). – Shepmaster Jun 04 '17 at 14:09
  • The question's title is `What optimizations does the Rust compiler make with loop versus while true?` – user2722968 Jun 04 '17 at 17:05
  • @Shepmaster I would think that `while(true) {}` vs. `loop{}` are sufficiently trivial and the differences localized enough that wildly different adjacent code will not be able to confuse the optimizers. Also, MIR happens before optimization AIUI – the8472 Jun 04 '17 at 17:38
  • @the8472 I **think** so as well, but I cannot *prove* something by just thinking it to be true. Concretely, [the result type of `loop` differs from that of `while true`](https://play.integer32.com/?gist=193b0502f8172cf2ad7378813924ed1a&version=stable). Are there optimizations that can be made based on that piece of information? I don't know. Additionally, having two pieces of code that do the same thing in different ways often *doesn't* optimize the same way. Autovectorization is a prime example of such cases. – Shepmaster Jun 04 '17 at 17:50
  • @the8472 *MIR happens before optimization* I'm not completely sure the connection of that and this issue, but [there are passes in the compiler that seem to indicate that there are optimization passes **on** MIR](https://github.com/rust-lang/rust/blob/341f4534488a3f56b8b9e188c1f4f52ed7707389/src/librustc_driver/driver.rs#L916-L943). Anecdotally, I've also heard of people wanting to perform optimization at that level. – Shepmaster Jun 04 '17 at 18:39