perf(ast): reduce allocations in With.MarshalJSON

Replace map[string]any with a struct for JSON serialization.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
This commit is contained in:
Ville Vesilehto
2026-01-10 08:58:18 +02:00
committed by Stephan Renatus
parent a938b9202e
commit 000055dff0
2 changed files with 25 additions and 6 deletions
+12 -6
View File
@@ -1729,16 +1729,22 @@ func (w *With) SetLoc(loc *Location) {
w.Location = loc
}
// withJSON is used for JSON serialization of With to avoid map allocation overhead.
// Field order is alphabetical to match previous map-based output.
type withJSON struct {
Location *Location `json:"location,omitempty"`
Target *Term `json:"target"`
Value *Term `json:"value"`
}
func (w *With) MarshalJSON() ([]byte, error) {
data := map[string]any{
"target": w.Target,
"value": w.Value,
data := withJSON{
Target: w.Target,
Value: w.Value,
}
if astJSON.GetOptions().MarshalOptions.IncludeLocation.With {
if w.Location != nil {
data["location"] = w.Location
}
data.Location = w.Location
}
return json.Marshal(data)
+13
View File
@@ -157,3 +157,16 @@ func BenchmarkRuleMarshalJSON(b *testing.B) {
})
}
}
func BenchmarkWithMarshalJSON(b *testing.B) {
module := MustParseModule(`
package test
allow if { input.x with input as {"x": true} }
`)
with := module.Rules[0].Body[0].With[0]
for b.Loop() {
_, _ = json.Marshal(with)
}
}