diff --git a/internal/gui/api.go b/internal/gui/api.go index adb034675..1fb29b085 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -3006,10 +3006,12 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r end = append(end, '\n') var row bytes.Buffer enc := json.NewEncoder(&row) - // encode is row i as Marshal gives it: Encode ends it with a newline + // encode is row i as Marshal gives it: Encode ends it with a newline. + // It is handed a pointer: rows[i] as an any was a copy of the row + // allocated for each row of each poll, ~2.7 MB a Sessions poll. encode := func(i int) ([]byte, error) { row.Reset() - if err := enc.Encode(rows[i]); err != nil { + if err := enc.Encode(&rows[i]); err != nil { return nil, err } return row.Bytes()[:row.Len()-1], nil diff --git a/internal/gui/writejsonrows_buf_test.go b/internal/gui/writejsonrows_buf_test.go index f89b3a592..44352d9fb 100644 --- a/internal/gui/writejsonrows_buf_test.go +++ b/internal/gui/writejsonrows_buf_test.go @@ -76,3 +76,26 @@ func TestWriteJSONRowsWritesWhatMarshalDid(t *testing.T) { t.Fatalf("delta\n got %q\nwant %q", w.Body, want) } } + +// TestJSONRowsNotCopiedEach: a poll whose answer the page has already +// encodes every row for its hash, and each row handed to the encoder as +// an any was a copy allocated for it, ~2.7 MB a Sessions poll. +func TestJSONRowsNotCopiedEach(t *testing.T) { + if raceOn { + t.Skip("-race: sync.Pool drops what it holds, so allocations are not what a build allocates") + } + rows := make([]rowsBufRow, 2000) + for i := range rows { + rows[i] = rowsBufRow{Name: "row", Note: "a note", N: float64(i)} + } + w := httptest.NewRecorder() + writeJSONRows(w, httptest.NewRequest("GET", "/x", nil), "rows", rows, struct{}{}) + r := httptest.NewRequest("GET", "/x", nil) + r.Header.Set("X-Magpie-Had", w.Header().Get("X-Magpie-Tag")) + allocs := testing.AllocsPerRun(5, func() { + writeJSONRows(httptest.NewRecorder(), r, "rows", rows, struct{}{}) + }) + if allocs > float64(len(rows))/10 { + t.Fatalf("a poll of %d rows the page has made %.0f allocations", len(rows), allocs) + } +}