forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringBuilderInLoop.cs
More file actions
41 lines (38 loc) · 1007 Bytes
/
StringBuilderInLoop.cs
File metadata and controls
41 lines (38 loc) · 1007 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
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
sb.Append("Hello ").Append(arg);
Console.WriteLine(sb);
}
}
}