Time for yet another micro-optimization!
Everyone knows that Strings are immutable in .NET, thus the StringBuilder class is very important for saving memory when dealing with manipulating large strings.
...but what about performance?
Interestingly, StringBuilder is just an all around better way to combine strings! It is more memory efficient, and less processor intensive; but not by much. Below is a comparison of performance between different ways of combine strings.
Unit Tests
[Theory]
[PropertyData("Args")]
public void StingPerformance(string[] args)
{
const int count = 1000000;
var sw1 = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = String.Empty;
foreach (var arg in args)
{
s += arg;
// Remember, the line above
// compiles into the following:
// s = String.Concat(s, arg);
}
}
sw1.Stop();
var sw2 = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
String.Concat(args);
}
sw2.Stop();
var sw3 = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var sb = new StringBuilder();
foreach (var arg in args)
sb.Append(arg);
}
sw3.Stop();
var msg = String.Format(
"Count: {0} - Add: {1} - Concat: {2} - Builder: {3}",
args.Length.ToString().PadLeft(2),
sw1.ElapsedMilliseconds.ToString().PadLeft(3),
sw2.ElapsedMilliseconds.ToString().PadLeft(3),
sw3.ElapsedMilliseconds.ToString().PadLeft(3));
Console.WriteLine(msg);
}
public static IEnumerable<IEnumerable<string[]>> Args
{
get
{
return new[]
{
new[] {new[] {"1"}},
new[] {new[] {"1", "2" }},
new[] {new[] {"1", "2", "3" }},
new[] {new[] {"1", "2", "3", "4" }},
new[] {new[] {"1", "2", "3", "4", "5" }},
// Etc...
};
}
}
Enjoy,
Tom
No comments:
Post a Comment