Files
codeql/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs
2026-07-07 14:09:48 +01:00

42 lines
1.0 KiB
C#

using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
var sb = new StringBuilder(); // $ Alert // BAD: Creation in loop
sb.Append("Hello ").Append(arg);
Console.WriteLine(sb);
}
}
void Fixed(string[] args)
{
var sb = new StringBuilder(); // GOOD: Not in loop
foreach (var arg in args)
{
sb.Clear();
sb.Append("Hello ").Append(arg);
Console.WriteLine(sb);
}
}
void ControlFlow(string[] args)
{
StringBuilder sb = null;
foreach (var arg in args)
{
if (sb == null)
sb = new StringBuilder(); // GOOD: Not in all control paths
else
sb.Clear();
lock (sb) sb = new StringBuilder(); // $ Alert // BAD: In all control paths
sb.Append("Hello ").Append(arg);
Console.WriteLine(sb);
}
}
}