I have created a small benchmarking console app for C# using the System.Diagnostics.StopWatch class to observe how long 3 methods take:
How I run the Benchmark:
public void Run()
{
Stopwatch sw = new Stopwatch();
sw.Start();
InitDirectly();
sw.Stop();
Console.WriteLine($"InitDirectly: {sw.Elapsed.TotalMilliseconds}ms");
sw.Reset();
sw.Start();
InitWithAdd();
sw.Stop();
Console.WriteLine($"InitWithAdd: {sw.Elapsed.TotalMilliseconds}ms");
sw.Reset();
sw.Start();
InitWithForLoop();
sw.Stop();
Console.WriteLine($"InitWithForLoop: {sw.Elapsed.TotalMilliseconds}ms");
}
Method 1:
private void InitListDirectly()
{
var list = new List<string>() {
"string",
"string",
"string",
//... up to a 100th entry
};
}
Method 2:
private void InitListViaAdd()
{
var list = new List<string>();
list.Add("string");
list.Add("string");
list.Add("string");
//... up to a 100th entry
}
Method 3:
private void InitListViaForLoop() {
var list = new List<string>();
for (int i = 0; i < 100; i++) {
list.Add("string");
}
}
Now starting the stopwatch before Method 1, then stopping. Same for Method 2.
- Method 1 took around ~0.800ms
- Method 2 took around ~1.000ms
- Method 3 took around ~0.120ms
Now I'm amazed, that the for-loop (Method 3) is so much faster. I expected Method 1 to be the fastest, since the other two methods have to call "Add(string)" and the third has to create a for-loop.
Why is Method 3 so much faster? Is that due to some compilermagic? Does it realize that the statement inside the for-loop will be identical for all it's iterations?
EDIT: I ran in debug mode.