Skip to content

Commit 7a4ccef

Browse files
authored
Optimize G115, G602, G407 analyzers to reduce allocations and memory (#1463)
* Optimize G115, G602, G407 analyzers to reduce allocations and memory * improve G407 coverage
1 parent 833d791 commit 7a4ccef

File tree

5 files changed

+752
-281
lines changed

5 files changed

+752
-281
lines changed

analyzers/bench_test.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,61 @@ func BenchmarkAnalysisG602_Wide(b *testing.B) {
185185
func BenchmarkAnalysisG407_Deep(b *testing.B) {
186186
benchmarkAnalyzerStress(b, "G407", func() string { return generateG407Stress(1000) })
187187
}
188+
189+
func generateComplex(functions, complexity int) string {
190+
var sb strings.Builder
191+
sb.WriteString("package main\n")
192+
sb.WriteString("import (\n")
193+
sb.WriteString("\t\"math\"\n")
194+
sb.WriteString("\t\"crypto/cipher\"\n")
195+
sb.WriteString(")\n")
196+
197+
// Generate helper functions that call each other
198+
for i := range functions {
199+
fmt.Fprintf(&sb, "func complexFunction%d(x int64, s []byte, gcm cipher.AEAD) {\n", i)
200+
201+
// G115 logic: conversions in branches
202+
for j := range complexity {
203+
fmt.Fprintf(&sb, "\tif x > %d && x < math.MaxInt64 {\n", j)
204+
fmt.Fprintf(&sb, "\t\t_ = int8(x)\n")
205+
fmt.Fprintf(&sb, "\t}\n")
206+
}
207+
208+
// G602 logic: slice operations
209+
fmt.Fprintf(&sb, "\t_ = s[%d]\n", i%10)
210+
for j := range complexity {
211+
fmt.Fprintf(&sb, "\tif len(s) > %d {\n", j)
212+
fmt.Fprintf(&sb, "\t\t_ = s[%d]\n", j)
213+
fmt.Fprintf(&sb, "\t}\n")
214+
}
215+
216+
// G407 logic: nonce passing (simulated)
217+
fmt.Fprintf(&sb, "\tnonce := []byte(\"hardcoded_nonce_%d\")\n", i)
218+
fmt.Fprintf(&sb, "\tgcm.Seal(nil, nonce, s, nil)\n")
219+
220+
// Call next function if not last
221+
if i < functions-1 {
222+
fmt.Fprintf(&sb, "\tcomplexFunction%d(x, s, gcm)\n", i+1)
223+
}
224+
sb.WriteString("}\n")
225+
}
226+
227+
sb.WriteString("func run_stress() {\n")
228+
sb.WriteString("\ts := make([]byte, 10000)\n")
229+
sb.WriteString("\tcomplexFunction0(100, s, nil)\n")
230+
sb.WriteString("}\n")
231+
232+
return sb.String()
233+
}
234+
235+
func BenchmarkAnalysisG115_Complex(b *testing.B) {
236+
benchmarkAnalyzerStress(b, "G115", func() string { return generateComplex(50, 20) })
237+
}
238+
239+
func BenchmarkAnalysisG602_Complex(b *testing.B) {
240+
benchmarkAnalyzerStress(b, "G602", func() string { return generateComplex(50, 20) })
241+
}
242+
243+
func BenchmarkAnalysisG407_Complex(b *testing.B) {
244+
benchmarkAnalyzerStress(b, "G407", func() string { return generateComplex(50, 20) })
245+
}

0 commit comments

Comments
 (0)