Skip to content

Commit 4bb9b61

Browse files
committed
strings: lower running time of TestCompareStrings
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 <[email protected]>
1 parent 6fe8ee7 commit 4bb9b61

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/strings/compare_test.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"internal/testenv"
1212
. "strings"
1313
"testing"
14+
"unsafe"
1415
)
1516

1617
var compareTests = []struct {
@@ -53,6 +54,12 @@ func TestCompareIdenticalString(t *testing.T) {
5354
}
5455

5556
func TestCompareStrings(t *testing.T) {
57+
// unsafeString converts a []byte to a string with no allocation.
58+
// The caller must not modify b while the result string is in use.
59+
unsafeString := func(b []byte) string {
60+
return *(*string)(unsafe.Pointer(&b))
61+
}
62+
5663
lengths := make([]int, 0) // lengths to test in ascending order
5764
for i := 0; i <= 128; i++ {
5865
lengths = append(lengths, i)
@@ -79,7 +86,7 @@ func TestCompareStrings(t *testing.T) {
7986
b[i] = 9
8087
}
8188

82-
sa, sb := string(a), string(b)
89+
sa, sb := unsafeString(a), unsafeString(b)
8390
cmp := Compare(sa[:len], sb[:len])
8491
if cmp != 0 {
8592
t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
@@ -96,12 +103,12 @@ func TestCompareStrings(t *testing.T) {
96103
}
97104
for k := lastLen; k < len; k++ {
98105
b[k] = a[k] - 1
99-
cmp = Compare(string(a[:len]), string(b[:len]))
106+
cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
100107
if cmp != 1 {
101108
t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
102109
}
103110
b[k] = a[k] + 1
104-
cmp = Compare(string(a[:len]), string(b[:len]))
111+
cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
105112
if cmp != -1 {
106113
t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)
107114
}

0 commit comments

Comments
 (0)