aboutsummaryrefslogtreecommitdiff
path: root/src/strings
diff options
context:
space:
mode:
authorKeith Randall <keithr@alum.mit.edu>2018-11-03 22:57:52 -0700
committerKeith Randall <khr@golang.org>2018-11-04 18:55:55 +0000
commit4bb9b61677e937d1f473c27607da3608d0fa7099 (patch)
tree2ebab9cf02b0a4d153e32295fe7cfc084f72a25d /src/strings
parent6fe8ee78e9b4870ebc1de2b5cfd6170a78a56c00 (diff)
downloadgo-4bb9b61677e937d1f473c27607da3608d0fa7099.tar.gz
go-4bb9b61677e937d1f473c27607da3608d0fa7099.zip
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 <bradfitz@golang.org>
Diffstat (limited to 'src/strings')
-rw-r--r--src/strings/compare_test.go13
1 files changed, 10 insertions, 3 deletions
diff --git a/src/strings/compare_test.go b/src/strings/compare_test.go
index 5d5334461c..94554e0af7 100644
--- a/src/strings/compare_test.go
+++ b/src/strings/compare_test.go
@@ -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)
}