How to check if [] byte is all zeros in go

Is there a way to check if a byte chunk is empty or 0 without checking each element or using reflection?

theByteVar := make([]byte, 128)

if "theByteVar is empty or zeroes" {
   doSomething()
}

One solution that seems odd to me was to save an empty byte array for comparison.

theByteVar := make([]byte, 128)
emptyByteVar := make([]byte, 128)

// fill with anything
theByteVar[1] = 2

if reflect.DeepEqual(theByteVar,empty) == false {
   doSomething(theByteVar)
}

Of course, there should be a better / quick solution.

thank

UPDATE has done some comparisons for 1000 loops, and the reflection method is the worst to date ...

Equal Loops: 1000 in true in 19.197µs
Contains Loops: 1000 in true in 34.507µs
AllZero Loops: 1000 in true in 117.275µs
Reflect Loops: 1000 in true in 14.616277ms
+4
source share
2 answers

bytes.Equal bytes.Contains , . https://play.golang.org/p/mvUXaTwKjP, haven 't , , , . , .

+2

, , ( ) 2 .

for :

for _, v := range theByteVar {
    if v != 0 {
        doSomething(theByteVar)
        break
    }
}

, :

func allZero(s []byte) bool {
    for _, v := range s {
        if v != 0 {
            return false
        }
    }
    return true
}

:

if !allZero(theByteVar) {
    doSomething(theByteVar)
}
+2

Source: https://habr.com/ru/post/1683013/


All Articles