A few days ago I discovered a rustc hacking screencast that shows how it’s possible to add support for negative subscripts in Rust and, having used Python extensively, I realized that I somewhat miss a concise way of accessing elements relative to the last one.
looks more concise and is at least as easy to understand as
But then, I put on my performance hat and wondered if there is a price for this simplicity. So first, I checked out the bytecode and saw that the shorter Python version results in a shorter list of bytecode instructions
instead of
After seeing this bytecode, I was almost sure that ls[-1]
would be faster than ls[len(ls)-1]
but we don’t rely on gut feeling, so let’s get some numbers.
Yay, this is one of those awesome cases when simple and beautiful solutions are also faster, in fact, almost 3X faster! Now I’m even more eager to see this feature being supported in Rust.
phew... for a second I thought the intuitive guess will be wrong. I'm glad it is not. thanks for the post!