check if bytes is all nulls
__peter__ at web.de
Sun Apr 1 14:23:18 EDT 2018
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.
Things you might try:
data = ... bytes ...
Worst case: creates another len(data)-1 byte string
search = re.compile(b"[^\0x00]").search
# actual check
search(data) is not None
More information about the Python-list