decodeJSON remembered that a body of 32KB or more was valid (validMemo), but each decode of it still walked every byte of the conversation to find its members: a request's readers (the model and stream flag, the metadata, max tokens, the messages, the tools...) decode the same body a dozen times, each into a few members. Where the top level's members are is now remembered with the body's validity (longBody), and fillJSON fills a struct or map at the top from those spans; a member the type doesn't want is passed over without a walk. A body under 32KB, or one not an object, is decoded as before. Test: TestDecodeJSONSplitsALongBodyOnce: 20 decodes of one long body into five types (a struct, a slice inside one, a pointer, a map of RawMessage, a nested struct) split it once, and each gets what encoding/json gives. Broken by hand (members never remembered): red, "split 21 times over 20 decodes, want 1". BenchmarkDecodeReaders (one 200KB body decoded into three small structs, as a request's readers do; -test.cpu 1, user+sys CPU of the whole binary, 3000 iterations minus a 30-iteration run, two rounds; load average ~450, so CPU time, not wall ns/op): before 1.26 / 1.25 s (0.09-0.11 s at 30) ~383 us per request's three decodes after 0.26 / 0.26 s (0.07-0.11 s at 30) ~57 us Allocations are unchanged (25 allocs, ~358B per iteration). BenchmarkGroupOverhead's 200KB request moved within its noise (12x20 p0/m1 22.16 -> 19.30/21.45 cpu-ms/op; 30x60 g4 43.22/48.49 -> 43.86/45.24). Run: go test ./internal/gateway -run 'JSON|Json|Decode|Fill|Memo' -count 1: ok (23.5s).
36 lines
908 B
Go
36 lines
908 B
Go
package gateway
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// BenchmarkDecodeReaders is a request's readers decoding one 200KB body,
|
|
// each into the few members it wants: the model and stream flag, the
|
|
// metadata, the max tokens.
|
|
func BenchmarkDecodeReaders(b *testing.B) {
|
|
body := []byte(`{"model":"claude-x","stream":true,"max_tokens":9,"messages":[{"role":"user","content":"` +
|
|
strings.Repeat("a long prompt with \\\"quotes\\\" and words ", 5000) + `"}],"metadata":{"user_id":"u"}}`)
|
|
b.SetBytes(int64(len(body)))
|
|
b.ReportAllocs()
|
|
for b.Loop() {
|
|
var a struct {
|
|
Model string `json:"model"`
|
|
Stream bool `json:"stream"`
|
|
}
|
|
var e struct {
|
|
Metadata struct {
|
|
UserID string `json:"user_id"`
|
|
} `json:"metadata"`
|
|
}
|
|
var m struct {
|
|
Max int `json:"max_tokens"`
|
|
}
|
|
for _, dst := range []any{&a, &e, &m} {
|
|
if err := decodeJSON(body, dst); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
}
|