Files
codeql/csharp/ql/test/query-tests/Performance/StringBuilderInLoop/StringBuilderInLoop.cs
Owen Mansel-Chan 11e99a03d5 C#
2026-06-10 22:57:22 +02: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(); // BAD: Creation in loop // $ Alert
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(); // BAD: In all control paths // $ Alert
sb.Append("Hello ").Append(arg);
Console.WriteLine(sb);
}
}
}