From: Kir Kolyshkin Date: Thu, 2 Dec 2021 03:48:58 +0000 (-0800) Subject: syscall: optimize Byte{Ptr,Slice}FromString X-Git-Tag: go1.19beta1~901 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=0d651041a9f48bbd1456317dfc784cdfa253e877;p=gostls13.git syscall: optimize Byte{Ptr,Slice}FromString Use bytealg.IndexByteString(str, 0) instead of looping through the string to check for a zero byte. A quick and dirty benchmark shows 10x performance improvement (on amd64 machine, using go 1.17.3). BytePtrFromString is used by many functions with string arguments. This change should make many functions in os package, such as those accepting a filename (os.Open, os.Stat, etc.), a tad faster. PS I am aware that syscall package is deprecated and frozen, but this change is mainly for the os package and the likes. The alternative would be for os to switch to x/sys, which is a much bigger change. Change-Id: I18fdd50f9fbfe0a23a4a71bc4bd0a5f5b0eaa475 Reviewed-on: https://go-review.googlesource.com/c/go/+/368457 Reviewed-by: Tobias Klauser Reviewed-by: Emmanuel Odeke Run-TryBot: Ian Lance Taylor TryBot-Result: Gopher Robot --- diff --git a/src/syscall/syscall.go b/src/syscall/syscall.go index 91173033ee..98e3005253 100644 --- a/src/syscall/syscall.go +++ b/src/syscall/syscall.go @@ -26,6 +26,8 @@ // package syscall +import "internal/bytealg" + //go:generate go run ./mksyscall_windows.go -systemdll -output zsyscall_windows.go syscall_windows.go security_windows.go // StringByteSlice converts a string to a NUL-terminated []byte, @@ -45,10 +47,8 @@ func StringByteSlice(s string) []byte { // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func ByteSliceFromString(s string) ([]byte, error) { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return nil, EINVAL - } + if bytealg.IndexByteString(s, 0) != -1 { + return nil, EINVAL } a := make([]byte, len(s)+1) copy(a, s)