]> Cypherpunks repositories - gostls13.git/commitdiff
strconv: some allocation tests
authorBrad Fitzpatrick <bradfitz@golang.org>
Tue, 13 Dec 2011 22:49:26 +0000 (14:49 -0800)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 13 Dec 2011 22:49:26 +0000 (14:49 -0800)
R=rsc, r
CC=golang-dev
https://golang.org/cl/5477084

src/pkg/strconv/ftoa_test.go
src/pkg/strconv/itoa_test.go

index a6205ac4777e601ac5336479d3587a25c27e298e..40c71a28b4dd5320153492b8ef79a5c2f8e05415 100644 (file)
@@ -149,6 +149,23 @@ func TestFtoa(t *testing.T) {
        }
 }
 
+func TestAppendFloatDoesntAllocate(t *testing.T) {
+       n := numAllocations(func() {
+               var buf [64]byte
+               AppendFloat(buf[:0], 1.23, 'g', 5, 64)
+       })
+       want := 1 // TODO(bradfitz): this might be 0, once escape analysis is better
+       if n != want {
+               t.Errorf("with local buffer, did %d allocations, want %d", n, want)
+       }
+       n = numAllocations(func() {
+               AppendFloat(globalBuf[:0], 1.23, 'g', 5, 64)
+       })
+       if n != 0 {
+               t.Errorf("with reused buffer, did %d allocations, want 0", n)
+       }
+}
+
 func BenchmarkFormatFloatDecimal(b *testing.B) {
        for i := 0; i < b.N; i++ {
                FormatFloat(33909, 'g', -1, 64)
index e0213ae9afecd4d1540b2644f9a255abaa321cd7..d4b09a5d87d12845d824e06c1b68c93912f6df32 100644 (file)
@@ -5,6 +5,7 @@
 package strconv_test
 
 import (
+       "runtime"
        . "strconv"
        "testing"
 )
@@ -125,6 +126,33 @@ func TestUitoa(t *testing.T) {
        }
 }
 
+func numAllocations(f func()) int {
+       runtime.UpdateMemStats()
+       n0 := runtime.MemStats.Mallocs
+       f()
+       runtime.UpdateMemStats()
+       return int(runtime.MemStats.Mallocs - n0)
+}
+
+var globalBuf [64]byte
+
+func TestAppendUintDoesntAllocate(t *testing.T) {
+       n := numAllocations(func() {
+               var buf [64]byte
+               AppendInt(buf[:0], 123, 10)
+       })
+       want := 1 // TODO(bradfitz): this might be 0, once escape analysis is better
+       if n != want {
+               t.Errorf("with local buffer, did %d allocations, want %d", n, want)
+       }
+       n = numAllocations(func() {
+               AppendInt(globalBuf[:0], 123, 10)
+       })
+       if n != 0 {
+               t.Errorf("with reused buffer, did %d allocations, want 0", n)
+       }
+}
+
 func BenchmarkFormatInt(b *testing.B) {
        for i := 0; i < b.N; i++ {
                for _, test := range itob64tests {