From 826bb1f7e8850f0d7b068a85222df71ad2af30ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20S=CC=8Ctibrany=CC=81?= Date: Thu, 12 Dec 2019 16:06:34 +0100 Subject: [PATCH] Convert string to bytes once only when doing string filtering. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes it slightly faster: name old time/op new time/op delta ContainsFilter-4 18.2ns ± 2% 9.8ns ± 1% -46.20% (p=0.000 n=10+8) name old alloc/op new alloc/op delta ContainsFilter-4 0.00B 0.00B ~ (all equal) name old allocs/op new allocs/op delta ContainsFilter-4 0.00 0.00 ~ (all equal) Signed-off-by: Peter Štibraný --- pkg/logql/ast.go | 6 ++++-- pkg/logql/ast_test.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/pkg/logql/ast.go b/pkg/logql/ast.go index b619f2738b97..e5d55eb0d7f5 100644 --- a/pkg/logql/ast.go +++ b/pkg/logql/ast.go @@ -138,13 +138,15 @@ func (e *filterExpr) Filter() (Filter, error) { } case labels.MatchEqual: + mb := []byte(e.match) f = func(line []byte) bool { - return bytes.Contains(line, []byte(e.match)) + return bytes.Contains(line, mb) } case labels.MatchNotEqual: + mb := []byte(e.match) f = func(line []byte) bool { - return !bytes.Contains(line, []byte(e.match)) + return !bytes.Contains(line, mb) } default: diff --git a/pkg/logql/ast_test.go b/pkg/logql/ast_test.go index db321b300db5..f26e6d77cbb7 100644 --- a/pkg/logql/ast_test.go +++ b/pkg/logql/ast_test.go @@ -111,3 +111,25 @@ func Test_FilterMatcher(t *testing.T) { }) } } + +func BenchmarkContainsFilter(b *testing.B) { + expr, err := ParseLogSelector(`{app="foo"} |= "foo"`) + if err != nil { + b.Fatal(err) + } + + f, err := expr.Filter() + if err != nil { + b.Fatal(err) + } + + line := []byte("hello world foo bar") + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + if !f(line) { + b.Fatal("doesn't match") + } + } +}