From 9564d2a833a87b60d28b26a69e23288ef73e3958 Mon Sep 17 00:00:00 2001 From: "Bryan C. Mills" Date: Tue, 28 Apr 2020 16:10:03 -0400 Subject: [PATCH] unsafeslice: make TestStringAllocs more robust to inlining and DCE Use the same technique as in the Benchmark functions to prevent the compiler from eliminating the converted value, and thus potentially also the conversion itself (especially in unsafe mode). Tests still pass alll the way back to go1.9.7. --- unsafeslice_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/unsafeslice_test.go b/unsafeslice_test.go index 65993c8..c51a4c6 100644 --- a/unsafeslice_test.go +++ b/unsafeslice_test.go @@ -162,9 +162,13 @@ func ExampleAsString() { func TestStringAllocs(t *testing.T) { t.Run("OfString", func(t *testing.T) { s := "Hello, world!" + + var b []byte avg := testing.AllocsPerRun(1000, func() { - _ = unsafeslice.OfString(s) + b = unsafeslice.OfString(s) }) + runtime.KeepAlive(b) + if avg > 0.01+maxStringAllocs { t.Errorf("unsafeslice.OfString made %v allocations; want %d", avg, maxStringAllocs) } @@ -172,9 +176,13 @@ func TestStringAllocs(t *testing.T) { t.Run("AsString", func(t *testing.T) { b := []byte("Hello, world!") + + var s string avg := testing.AllocsPerRun(1000, func() { - _ = unsafeslice.AsString(b) + s = unsafeslice.AsString(b) }) + runtime.KeepAlive(s) + if avg > 0.01+maxStringAllocs { t.Errorf("unsafeslice.OfString made %v allocations; want %d", avg, maxStringAllocs) }