Performance difference among Range, RangeInclusive and reversed

In general, you should use half-open ranges (aka Range), because all else being equal they're the best, as has been known since 1982: E.W. Dijkstra Archive: Why numbering should start at zero (EWD 831)

If you really need inclusive ranges, then use them, but remember that they're fundamentally more complicated -- they have to worry about both the endpoint of the range and the potential for wrapping. So because they're more complicated, you shouldn't expect them to be as fast in every situation.

And as my post above says, if you have a tiny loop body where a few instructions of overhead might matter, use internal iteration instead of for loops. It's not just RangeInclusive where that helps, but also a bunch of iterators adapters too -- Chain being the most common example.

But if you're doing material work in the loop body, it just doesn't matter. Any difference between .. and ..= will completely disappear compared to the cost of reading a file, for example.

4 Likes