]> Cypherpunks repositories - gostls13.git/commitdiff
syscall: optimize Byte{Ptr,Slice}FromString
authorKir Kolyshkin <kolyshkin@gmail.com>
Thu, 2 Dec 2021 03:48:58 +0000 (19:48 -0800)
committerEmmanuel Odeke <emmanuel@orijtech.com>
Mon, 28 Mar 2022 16:55:57 +0000 (16:55 +0000)
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 <tobias.klauser@gmail.com>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>

src/syscall/syscall.go

index 91173033eecf81973237c850b4c69552ead376a8..98e30052531a52b73482aabe0c520b5fa5075877 100644 (file)
@@ -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)