Software Bits Newsletter

Share this post
Negative subscripts.
softwarebits.substack.com

Negative subscripts.

Or when simple does not mean slower.

Taras Tsugrii
Nov 6, 2021
Comment2
Share

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.

Comment2
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

Yacob Cohen-Arazi
Nov 6, 2021

phew... for a second I thought the intuitive guess will be wrong. I'm glad it is not. thanks for the post!

Expand full comment
Reply
1 reply by Taras Tsugrii
1 more comments…
TopNewCommunity

No posts

Ready for more?

© 2022 Taras Tsugrii
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing