mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-12 19:32:48 -06:00
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:
committed by
Stephan Renatus
parent
a938b9202e
commit
000055dff0
+12
-6
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user