Skip to content

Commit

Permalink
strings: lower running time of TestCompareStrings
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
randall77 committed Nov 4, 2018
1 parent 6fe8ee7 commit 4bb9b61
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/strings/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"internal/testenv"
. "strings"
"testing"
"unsafe"
)

var compareTests = []struct {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
}
Expand Down

0 comments on commit 4bb9b61

Please sign in to comment.