Skip to content

Commit

Permalink
Improve performance of metric expression matcher (#5864)
Browse files Browse the repository at this point in the history
Refactored env struct to avoid creating closure functions for every
expression evaluation operation. This reduced the allocations and
increased the speed.

Improvements:

$ benchstat old.txt new.txt
name          old time/op    new time/op    delta
ExprFilter-8     537µs ± 2%     476µs ± 1%  -11.33%  (p=0.000 n=9+10)

name          old alloc/op   new alloc/op   delta
ExprFilter-8     151kB ± 0%     102kB ± 0%  -32.43%  (p=0.000 n=8+8)

name          old allocs/op  new allocs/op  delta
ExprFilter-8     8.44k ± 0%     6.39k ± 0%  -24.24%  (p=0.000 n=10+10)
  • Loading branch information
tigrannajaryan committed Oct 21, 2021
1 parent b90d1f0 commit 9ceb2ff
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
29 changes: 15 additions & 14 deletions internal/coreinternal/processor/filterexpr/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,17 @@ type Matcher struct {

type env struct {
MetricName string
// TODO: replace this with GetLabel func(key string) (string,bool)
HasLabel func(key string) bool
Label func(key string) string
attributes pdata.AttributeMap
}

func (e *env) HasLabel(key string) bool {
_, ok := e.attributes.Get(key)
return ok
}

func (e *env) Label(key string) string {
v, _ := e.attributes.Get(key)
return v.StringVal()
}

func NewMatcher(expression string) (*Matcher, error) {
Expand Down Expand Up @@ -100,21 +108,14 @@ func (m *Matcher) matchEnv(metricName string, attributes pdata.AttributeMap) (bo
return m.match(createEnv(metricName, attributes))
}

func createEnv(metricName string, attributes pdata.AttributeMap) env {
return env{
func createEnv(metricName string, attributes pdata.AttributeMap) *env {
return &env{
MetricName: metricName,
HasLabel: func(key string) bool {
_, ok := attributes.Get(key)
return ok
},
Label: func(key string) string {
v, _ := attributes.Get(key)
return v.StringVal()
},
attributes: attributes,
}
}

func (m *Matcher) match(env env) (bool, error) {
func (m *Matcher) match(env *env) (bool, error) {
result, err := m.v.Run(m.program, env)
if err != nil {
return false, err
Expand Down
2 changes: 1 addition & 1 deletion internal/coreinternal/processor/filterexpr/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestCompileExprError(t *testing.T) {
func TestRunExprError(t *testing.T) {
matcher, err := NewMatcher("foo")
require.NoError(t, err)
matched, _ := matcher.match(env{})
matched, _ := matcher.match(&env{})
require.False(t, matched)
}

Expand Down

0 comments on commit 9ceb2ff

Please sign in to comment.