Commit 4bb9b616 authored by Keith Randall's avatar Keith Randall Committed by Keith Randall

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/147358Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
parent 6fe8ee78
......@@ -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)
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment