Reference

Chris Angelico rosuav at gmail.com
Tue Mar 4 06:24:03 CET 2014


On Tue, Mar 4, 2014 at 3:52 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> This is why, unless performance is *really* critical, one should normally
> write x*2 when multiplying x by 2 rather than x >> 1. (And in Python, the
> overhead means that there is no real performance benefit to using bit
> shifts instead of multiplication or division.)

In most C compilers today (C being where x << 1 would be used rather
than x * 2), the expressions would be equivalent, so you can still
express it as x * 2 and let the compiler turn that into a bit shift.
(And it's possible that "x * 5" will become "x << 2 + x", too.)
Definitely go for the expressive version unless you've actually tested
that the obscure version is faster.

(Of course, that doesn't mean the bit-shift operators should never be
used. If you're trying to pack three tiny integers into a single
larger integer, you probably want bit shifts and bitwise or, not
multiplication and addition, even though either would work.)

Code should look like its intent. Warping it around performance is
hardly ever worthwhile.

ChrisA



More information about the Python-list mailing list