Fastest way to check if a byte array is all zeros

前端 未结 5 842
栀梦
栀梦 2021-02-03 18:06

I have a byte[4096] and was wondering what the fastest way is to check if all values are zero?

Is there any way faster than doing:

byte[] b          


        
5条回答
  •  萌比男神i
    2021-02-03 18:43

    Someone suggested checking 4 or 8 bytes at a time. You actually can do this in Java:

    LongBuffer longBuffer = ByteBuffer.wrap(b).asLongBuffer();
    while (longBuffer.hasRemaining()) {
        if (longBuffer.get() != 0) {
            return false;
        }
    }
    return true;
    

    Whether this is faster than checking byte values is uncertain, since there is so much potential for optimization.

提交回复
热议问题