Hello.
I read an article about the performance of the string methods "a" + b
versus string.Format("a{1}", b) and decided to make a test.
There is my code in a WinForms application(VS 2005, but interested in both 2005/2008).
private void button1_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
Console.Write("1" + 2 + "3" + 4 + "5");
}
stopwatch.Stop();
Console.WriteLine("**********");
Console.WriteLine("'A'+'B'+'C'... 10 000 elapsed: {0}",
stopwatch.Elapsed.ToString());
Console.WriteLine("**********");
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
Console.Write(string.Format("1{0}3{1}5", 2, 4));
}
stopwatch.Stop();
Console.WriteLine("**********");
Console.WriteLine("string.Format((A)B(C)...) 10 000 elapsed: {0}",
stopwatch.Elapsed.ToString());
Console.WriteLine("**********");
}
on my machine the output is the following:
12345123451234512345123451234512345123451234512345123451...
'A'+'B'+'C'... 10 000 elapsed: 00:00:0 9.4217880
12345123451234512345123451234512345123451234512345123451...
string.Format((A)B(C)...) 10 000 elapsed: 00:00:0 9.8507060
So, the time is almost the same.
Now, I wonder how much memory I used. Is there a way to compare the memory usage and the GarbageCollector work?
I downloaded a trial .NET Memory Profiler... but maybe there is a more simple(code like above) way to detect the spent memory on both iterations?
Thanks.