Bitshifts and "And" vs Floor-division and Modular

Dave Angel d at davea.name
Thu Sep 6 21:46:12 EDT 2012


On 09/06/2012 09:30 PM, jimbo1qaz wrote:
> On Thursday, September 6, 2012 5:01:12 PM UTC-7, jimbo1qaz wrote:
>> Is it faster to use bitshifts or floor division? And which is better, & or %?
>>
>> All divisors and mods are power of 2, so are binary operations faster? And are they considered bad style?
> OK, I decided to change my code. Which raises a similar question: Which one is better for setting a bit of a byte: |= or +=, assuming each will only be run once? Intuitively, I think |=, but some timeits are inconclusive, mainly because I don't know how it works.

Maybe i should have been clearer in my message.  i don't think you'll
find a meaningful difference unless you're doing longs of a few hundred
digits.  So if the algorithm is to OR on a bit, please use a |=
augmented assignment.  not only will it ward off probable bugs when you
accidentally try to set the bit a second time, but it reads better for
the reader of the program.  The reader is more important than the compiler.

-- 

DaveA




More information about the Python-list mailing list