Skip to content

Commit

Permalink
unsafeslice: make TestStringAllocs more robust to inlining and DCE
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Bryan C. Mills committed Apr 28, 2020
1 parent 383676f commit 9564d2a
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions unsafeslice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,19 +162,27 @@ 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)
}
})

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)
}
Expand Down

0 comments on commit 9564d2a

Please sign in to comment.