Skip to content

Commit

Permalink
Ignore complexity of children in maps/slices (#382)
Browse files Browse the repository at this point in the history
When considering inlining maps/slices/arrays, apply a fixed cost and ignore the cost of the children.

If children are too expensive, they will not be inlined, but it shouldn't affect whether the map itself is inlined.

This only really applies when a map or slice type is aliased, otherwise it will not be considered for inlining.

Fixes #381
  • Loading branch information
klauspost authored Dec 9, 2024
1 parent 901ed00 commit c0009df
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
16 changes: 16 additions & 0 deletions _generated/def.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,19 @@ type NumberJSONSample struct {
Map map[string]json.Number
OE json.Number `msg:",omitempty"`
}

type Flobbity struct {
A Flobs `msg:"a,omitempty"`
B Flobs `msg:"b,omitempty"`
}

type Flobs []Flob

type Flob struct {
X Numberwang `msg:"x"`
Y int8 `msg:"y"`
Z int8 `msg:"z"`
W int32 `msg:"w"`
}

type Numberwang int8
13 changes: 10 additions & 3 deletions gen/elem.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ func (a *Array) Copy() Elem {
return &b
}

func (a *Array) Complexity() int { return 1 + a.Els.Complexity() }
func (a *Array) Complexity() int {
// We consider the complexity constant and leave the children to decide on their own.
return 2
}

// ZeroExpr returns the zero/empty expression or empty string if not supported. Unsupported for this case.
func (a *Array) ZeroExpr() string { return "" }
Expand Down Expand Up @@ -313,7 +316,10 @@ func (m *Map) Copy() Elem {
return &g
}

func (m *Map) Complexity() int { return 2 + m.Value.Complexity() }
func (m *Map) Complexity() int {
// Complexity of maps are considered constant. Children should decide on their own.
return 3
}

// ZeroExpr returns the zero/empty expression or empty string if not supported. Always "nil" for this case.
func (m *Map) ZeroExpr() string { return "nil" }
Expand Down Expand Up @@ -360,7 +366,8 @@ func (s *Slice) Copy() Elem {
}

func (s *Slice) Complexity() int {
return 1 + s.Els.Complexity()
// We leave the inlining decision to the slice children.
return 2
}

// ZeroExpr returns the zero/empty expression or empty string if not supported. Always "nil" for this case.
Expand Down

0 comments on commit c0009df

Please sign in to comment.