Optimize safemem.Zero

There is a loop that fills a byte array with zero-s. Let's use copy() instead
of setting elements one by one.

The new implementation is two time faster than the previous one and it is more
than 10x faster with the race detector.

Reported-by: syzbot+5f57d988a5f929af5a91@syzkaller.appspotmail.com
PiperOrigin-RevId: 369283919
This commit is contained in:
Andrei Vagin
2021-04-19 13:01:59 -07:00
committed by gVisor bot
parent 9b4cc3d43b
commit b0333d33a2
2 changed files with 18 additions and 2 deletions
+1
View File
@@ -14,6 +14,7 @@ go_library(
deps = [
"//pkg/gohacks",
"//pkg/safecopy",
"//pkg/sync",
"@org_golang_x_sys//unix:go_default_library",
],
)
+17 -2
View File
@@ -20,6 +20,7 @@ import (
"gvisor.dev/gvisor/pkg/gohacks"
"gvisor.dev/gvisor/pkg/safecopy"
"gvisor.dev/gvisor/pkg/sync"
)
// A Block is a range of contiguous bytes, similar to []byte but with the
@@ -223,8 +224,22 @@ func Copy(dst, src Block) (int, error) {
func Zero(dst Block) (int, error) {
if !dst.needSafecopy {
bs := dst.ToSlice()
for i := range bs {
bs[i] = 0
if !sync.RaceEnabled {
// If the race detector isn't enabled, the golang
// compiler replaces the next loop with memclr
// (https://github.com/golang/go/issues/5373).
for i := range bs {
bs[i] = 0
}
} else {
bsLen := len(bs)
if bsLen == 0 {
return 0, nil
}
bs[0] = 0
for i := 1; i < bsLen; i *= 2 {
copy(bs[i:], bs[:i])
}
}
return len(bs), nil
}