]> Cypherpunks repositories - gostls13.git/commitdiff
strings: lower running time of TestCompareStrings
authorKeith Randall <keithr@alum.mit.edu>
Sun, 4 Nov 2018 05:57:52 +0000 (22:57 -0700)
committerKeith Randall <khr@golang.org>
Sun, 4 Nov 2018 18:55:55 +0000 (18:55 +0000)
At each comparison, we're making a copy of the whole string.
Instead, use unsafe to share the string backing store with a []byte.

It reduces the test time from ~4sec to ~1sec on my machine
(darwin/amd64).  Some builders were having much more trouble with this
test (>3min), it may help more there.

Fixes #26174
Fixes #28573
Fixes #26155
Update #26473

Change-Id: Id5856fd26faf6ff46e763a088f039230556a4116
Reviewed-on: https://go-review.googlesource.com/c/147358
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
src/strings/compare_test.go

index 5d5334461c31060797832344f940d1645c781836..94554e0af794c5582e51240dfc46682058781b7c 100644 (file)
@@ -11,6 +11,7 @@ import (
        "internal/testenv"
        . "strings"
        "testing"
+       "unsafe"
 )
 
 var compareTests = []struct {
@@ -53,6 +54,12 @@ func TestCompareIdenticalString(t *testing.T) {
 }
 
 func TestCompareStrings(t *testing.T) {
+       // unsafeString converts a []byte to a string with no allocation.
+       // The caller must not modify b while the result string is in use.
+       unsafeString := func(b []byte) string {
+               return *(*string)(unsafe.Pointer(&b))
+       }
+
        lengths := make([]int, 0) // lengths to test in ascending order
        for i := 0; i <= 128; i++ {
                lengths = append(lengths, i)
@@ -79,7 +86,7 @@ func TestCompareStrings(t *testing.T) {
                        b[i] = 9
                }
 
-               sa, sb := string(a), string(b)
+               sa, sb := unsafeString(a), unsafeString(b)
                cmp := Compare(sa[:len], sb[:len])
                if cmp != 0 {
                        t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
@@ -96,12 +103,12 @@ func TestCompareStrings(t *testing.T) {
                }
                for k := lastLen; k < len; k++ {
                        b[k] = a[k] - 1
-                       cmp = Compare(string(a[:len]), string(b[:len]))
+                       cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
                        if cmp != 1 {
                                t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
                        }
                        b[k] = a[k] + 1
-                       cmp = Compare(string(a[:len]), string(b[:len]))
+                       cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
                        if cmp != -1 {
                                t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)
                        }