有没有一种方法可以检查字节片是否为空或为0,而无需检查每个元素或不使用反射?
theByteVar := make([]byte, 128)
if "theByteVar is empty or zeroes" {
doSomething()
}
Run Code Online (Sandbox Code Playgroud)
我发现似乎很奇怪的一种解决方案是保留一个空字节数组以进行比较。
theByteVar := make([]byte, 128)
emptyByteVar := make([]byte, 128)
// fill with anything
theByteVar[1] = 2
if reflect.DeepEqual(theByteVar,empty) == false {
doSomething(theByteVar)
}
Run Code Online (Sandbox Code Playgroud)
当然,必须有一个更好的/更快速的解决方案。
谢谢
UPDATE对1000个循环做了一些比较,而反射方式是迄今为止最差的。
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
Run Code Online (Sandbox Code Playgroud)