Get the latest tech news

The humble for loop in Rust


Rust has some really nice functional programming facilities built in, all around an iterator concept. Rust being focused on performance and low level control makes it possible to use this without paying a performance cost. Sometimes I still prefer to use the humble for loop though. In quite a few cases, it combines high performance with high readability. I thought I'd motivate why. …

Where it gets interesting is when I start to talk about 3, 10, or a 100 times faster, as these demonstrate real algorithmic differences that hold up in many contexts, and therefore can help guide our behavior. I suspect with the map() option the Rust compiler figures out it can avoid allocations altogether by simply writing over the original vector, while with the loop it can't. If we ignore the performance difference which is inherent to folding over a collection like this, I'd still argue the for loop is easier to read and write in this scenario.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of Rust

Rust

Photo of loop

loop

Related news:

News photo

Dioxus 0.6 – Crossplatform apps with Rust

News photo

Limbo: A complete rewrite of SQLite in Rust

News photo

Rust-Based, Memory-Safe PNG Decoders "Vastly Outperform" C-Based PNG Libraries