From 4bb9b61677e937d1f473c27607da3608d0fa7099 Mon Sep 17 00:00:00 2001 From: Keith Randall Date: Sat, 3 Nov 2018 22:57:52 -0700 Subject: [PATCH] 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 --- src/strings/compare_test.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/strings/compare_test.go b/src/strings/compare_test.go index 5d5334461c3106..94554e0af794c5 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) }