check if bytes is all nulls
MRAB
python at mrabarnett.plus.com
Sun Apr 1 14:21:25 EDT 2018
On 2018-04-01 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:
>
> sum(key) == 0 is invalid
> key == bytes(len(key)) is invalid
>
> I already considered precomputing the rhs value.
> Length of key is unknown, could be few bytes, could be megabytes.
>
Have you tried:
not key.lstrip(b'\x00')
? (Although the result of the lstrip could be as long as the original.)
Or:
set(key) == set(b'\x00')
? (The set will never have more than 256 members.)
More information about the Python-list
mailing list