Skip to content

Commit

Permalink
perf: GetField reduce allocations (#1195)
Browse files Browse the repository at this point in the history
reuse slice
  • Loading branch information
M4tteoP authored Nov 5, 2024
1 parent dee0676 commit de409e3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
11 changes: 6 additions & 5 deletions internal/corazawaf/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,9 +587,9 @@ func (tx *Transaction) GetField(rv ruleVariableParams) []types.MatchData {
}

// in the most common scenario filteredMatches length will be
// the same as matches length, so we avoid allocating per result
filteredMatches := make([]types.MatchData, 0, len(matches))

// the same as matches length, so we avoid allocating per result.
// We reuse the matches slice to store filtered results avoiding extra allocation.
filteredCount := 0
for _, c := range matches {
isException := false
lkey := strings.ToLower(c.Key())
Expand All @@ -600,10 +600,11 @@ func (tx *Transaction) GetField(rv ruleVariableParams) []types.MatchData {
}
}
if !isException {
filteredMatches = append(filteredMatches, c)
matches[filteredCount] = c
filteredCount++
}
}
matches = filteredMatches
matches = matches[:filteredCount]

if rv.Count {
count := len(matches)
Expand Down
14 changes: 14 additions & 0 deletions internal/corazawaf/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1291,6 +1291,20 @@ func TestTxGetField(t *testing.T) {
}
}

func BenchmarkTxGetField(b *testing.B) {
tx := makeTransaction(b)
rvp := ruleVariableParams{
Variable: variables.Args,
}
for i := 0; i < b.N; i++ {
tx.GetField(rvp)
}
if err := tx.Close(); err != nil {
b.Fatalf("Failed to close transaction: %s", err.Error())
}
b.ReportAllocs()
}

func TestTxProcessURI(t *testing.T) {
waf := NewWAF()
tx := waf.NewTransaction()
Expand Down

0 comments on commit de409e3

Please sign in to comment.