Optimize wire.Uint.save() to make only 1 Write() call.

Earlier wire.Uint.save() could make up to 10 Write() calls depending on how
large the Uint being marshaled was. Write() is an interface method call, so
this avoids the dynamic dispatch overhead. Furthermore, compressio's Write
implementations themselves do a bunch of fixed work per call and invoke more
interface functions.

Increased the scratch buffer in the wire.Writer to accommodate 10 bytes. The
wire.Uint can be marshaled into at most 10 bytes.

Before:

goos: linux
goarch: amd64
pkg: pkg/state/wire/wire
cpu: AMD EPYC 7B12
BenchmarkUintSave
BenchmarkUintSave-24    	37557860	        31.13 ns/op	       0 B/op	       0 allocs/op

After:

goos: linux
goarch: amd64
pkg: pkg/state/wire/wire
cpu: AMD EPYC 7B12
BenchmarkUintSave
BenchmarkUintSave-24    	129611625	         9.274 ns/op	       0 B/op	       0 allocs/op
PiperOrigin-RevId: 672679703
This commit is contained in:
Ayush Ranjan
2024-09-09 14:45:45 -07:00
committed by gVisor bot
parent f97dd13d1a
commit 905d769f6f
6 changed files with 56 additions and 30 deletions
+1 -1
View File
@@ -117,7 +117,7 @@ func BenchmarkEncoding(b *testing.B) {
b.ReportAllocs()
b.StartTimer()
for i := 0; i < n; i++ {
if _, err := algoInfo.Save(context.Background(), discard{}, v); err != nil {
if _, err := algoInfo.Save(context.Background(), io.Discard, v); err != nil {
b.Errorf("save failed: %v", err)
}
}
+2 -10
View File
@@ -19,6 +19,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"math"
"reflect"
"testing"
@@ -27,15 +28,6 @@ import (
"gvisor.dev/gvisor/pkg/state/pretty"
)
// discard is an implementation of wire.Writer.
type discard struct{}
// Write implements wire.Writer.Write.
func (discard) Write(p []byte) (int, error) { return len(p), nil }
// WriteByte implements wire.Writer.WriteByte.
func (discard) WriteByte(byte) error { return nil }
// checkEqual checks if two objects are equal.
//
// N.B. This only handles one level of dereferences for NaN. Otherwise we
@@ -103,7 +95,7 @@ func runTestCases(t *testing.T, shouldFail bool, prefix string, objects []any) {
t.Errorf("PrettyPrint(html=false) failed unexpected: %v", err)
}
}
if err := pretty.PrintHTML(discard{}, bytes.NewReader(saveBuffer.Bytes())); err != nil {
if err := pretty.PrintHTML(io.Discard, bytes.NewReader(saveBuffer.Bytes())); err != nil {
// See above.
if !shouldFail {
t.Errorf("PrettyPrint(html=true) failed unexpected: %v", err)