Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

slice

go

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

theByteVar := make([]byte, 128)

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

One solution which seems weird that I found was to keep 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)
}

For sure there must be a better/quicker solution.

Thanks

UPDATE did some comparison for 1000 loops and the reflect way is the worst by far...

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
like image 454
Jinxmcg Avatar asked Aug 04 '17 12:08

Jinxmcg


1 Answers

Comparing it with another slice containing only zeros, that requires reading (and comparing) 2 slices.

Using a single for loop will be more efficient here:

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

If you do need to use it in multiple places, wrap it in a utility function:

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

And then using it:

if !allZero(theByteVar) {
    doSomething(theByteVar)
}
like image 118
icza Avatar answered Nov 05 '22 10:11

icza