check if bytes is all nulls

bartc bc at freeuk.com
Sun Apr 1 14:43:45 EDT 2018


On 01/04/2018 18:55, Arkadiusz Bulski wrote:
> What would be the most performance efficient way of checking if a bytes is
> all zeros? Currently its `key == b'\x00' * len(key)` however, because its
> Python 2/3 compatible:

That doesn't too efficient, if you first have to construct a compatible 
object of all zeros.


> sum(key) == 0 is invalid
> key == bytes(len(key)) is invalid
> 
> I already considered precomputing the rhs value.
> Length of key is unknown,

(So how can you precompute the table?)

  could be few bytes, could be megabytes.
> 

How likely would be a block of all zeros? Or one that is all zeros but 
with a sparse smattering of non-zeros?

If not very, then just check the bytes one by one. If non-zero, you will 
know as soon as you see the first non-zero byte, possibly the first one.

def allzeros(a):
     for x in a:
         if x: return 0
     return 1


-- 
bartc



More information about the Python-list mailing list