From 1e9e775faf8aa332b15322a8532a8056fb9e466a Mon Sep 17 00:00:00 2001 From: Anton Petruhin Date: Mon, 20 Nov 2023 11:33:55 +0300 Subject: [PATCH] optimize `Pattern.WeakEqual` --- pattern.go | 16 ++++++++-------- pattern_test.go | 8 ++++++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/pattern.go b/pattern.go index 6c86ad0..7ee091c 100644 --- a/pattern.go +++ b/pattern.go @@ -53,16 +53,16 @@ func (p *Pattern) WeakEqual(other *Pattern) bool { if len(p.words) != len(other.words) { return false } - var matches int - for i, op := range other.words { - if p.words[i] == op { - matches++ + var diffs int + for i, ow := range other.words { + if p.words[i] != ow { + diffs++ + if diffs > 1 { + return false + } } } - if matches >= len(p.words)-1 { - return true - } - return false + return true } func NewPattern(input string) *Pattern { diff --git a/pattern_test.go b/pattern_test.go index ba6e579..2acdee6 100644 --- a/pattern_test.go +++ b/pattern_test.go @@ -82,6 +82,14 @@ func TestPatternWeakEqual(t *testing.T) { assert.False(t, NewPattern("foo bar baz").WeakEqual(NewPattern("baz bar foo"))) } +func BenchmarkPatternWeakEqual(b *testing.B) { + p1 := NewPattern("foo one two bar buz") + p2 := NewPattern("foo three four bar buz") + for n := 0; n < b.N; n++ { + p1.WeakEqual(p2) + } +} + func TestPatternRemoveQuotedAndBrackets(t *testing.T) { assert.Equal(t, "foo bar", removeQuotedAndBrackets(`foo 'squoted' bar`)) assert.Equal(t, "foo bar", removeQuotedAndBrackets(`foo 'squoted \'baz\'' bar`))