Ensure that Buffer.Marshal uses O(N) memory for N messages
(t *testing.T)
| 288 | |
| 289 | // Ensure that Buffer.Marshal uses O(N) memory for N messages |
| 290 | func TestBufferMarshalAllocs(t *testing.T) { |
| 291 | value := &pb2.OtherMessage{Key: proto.Int64(1)} |
| 292 | msg := &pb2.MyMessage{Count: proto.Int32(1), Others: []*pb2.OtherMessage{value}} |
| 293 | |
| 294 | for _, prealloc := range []int{0, 100, 10000} { |
| 295 | const count = 1000 |
| 296 | var b proto.Buffer |
| 297 | s := make([]byte, 0, proto.Size(msg)) |
| 298 | marshalAllocs := testing.AllocsPerRun(count, func() { |
| 299 | b.SetBuf(s) |
| 300 | err := b.Marshal(msg) |
| 301 | if err != nil { |
| 302 | t.Errorf("Marshal err = %q", err) |
| 303 | } |
| 304 | }) |
| 305 | |
| 306 | b.SetBuf(make([]byte, 0, prealloc)) |
| 307 | bufferAllocs := testing.AllocsPerRun(count, func() { |
| 308 | err := b.Marshal(msg) |
| 309 | if err != nil { |
| 310 | t.Errorf("Marshal err = %q", err) |
| 311 | } |
| 312 | }) |
| 313 | |
| 314 | if marshalAllocs != bufferAllocs { |
| 315 | t.Errorf("%v allocs/op when writing to a preallocated buffer", marshalAllocs) |
| 316 | t.Errorf("%v allocs/op when repeatedly appending to a buffer", bufferAllocs) |
| 317 | t.Errorf("expect amortized allocs/op to be identical") |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // Simple tests for bytes |
| 323 | func TestBytesPrimitives(t *testing.T) { |