From fa1b74d4fc904a8af6ccdbfd723658d03d5d31bc Mon Sep 17 00:00:00 2001
From: Eng Zer Jun <engzerjun@gmail.com>
Date: Wed, 25 Oct 2023 03:23:17 +0800
Subject: [PATCH] Avoid allocations with `(*regexp.Regexp).MatchString`

We should use `(*regexp.Regexp).MatchString` instead of
`(*regexp.Regexp).Match([]byte(...))` when matching string to avoid
unnecessary `[]byte` conversions and reduce allocations.

Example benchmark:

var defaultTagRegex = regexp.MustCompile("\n *#nosec")

func BenchmarkMatch(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := defaultTagRegex.Match([]byte("\n #nosec")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := defaultTagRegex.MatchString("\n #nosec"); !match {
			b.Fail()
		}
	}
}

goos: linux
goarch: amd64
pkg: github.com/securego/gosec/v2
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 5367033	       210.6 ns/op	       8 B/op	       1 allocs/op
BenchmarkMatchString-16    	 9321561	       126.3 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/securego/gosec/v2	3.606s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
---
 analyzer.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/analyzer.go b/analyzer.go
index 1fd1f56..bcb9143 100644
--- a/analyzer.go
+++ b/analyzer.go
@@ -557,8 +557,8 @@ func (gosec *Analyzer) ignore(n ast.Node) map[string]issue.SuppressionInfo {
 
 		for _, group := range groups {
 			comment := strings.TrimSpace(group.Text())
-			foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) || regexp.MustCompile("\n *"+noSecDefaultTag).Match([]byte(comment))
-			foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) || regexp.MustCompile("\n *"+noSecAlternativeTag).Match([]byte(comment))
+			foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) || regexp.MustCompile("\n *"+noSecDefaultTag).MatchString(comment)
+			foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) || regexp.MustCompile("\n *"+noSecAlternativeTag).MatchString(comment)
 
 			if foundDefaultTag || foundAlternativeTag {
 				gosec.stats.NumNosec++