Comment by tialaramex
2 hours ago
Rust only actually has a single loop, the other loops in Rust are just syntax sugar. Early in compilation the compiler will "de-sugar" a while or for loop into that ordinary infinite loop and so by the time your code is optimised it can't matter how you wrote the loop.
This answers the question Matt Godbolt had which caused him to create what would become Compiler Explorer, is a fancy modern for-each loop able to deliver the same perf as my 1970s loop? In Rust the answer is necessarily "Yes" because by the time the backend sees your program they're the same thing.
The reason Matt wanted to know is that obviously a for-each loop often has better ergonomics, so if they mean the same thing we should prefer our team to write this - but if they're slower that's a tough question, should we trade performance for clarity? The "Yes" answer that Matt found for C++ and which is baked into Rust means you don't need to make that trade decision, write whatever is easier to understand and maintain.
No comments yet
Contribute on Hacker News ↗