useful tool if you choose proper test methods.

Jan 25, 2010 at 7:02 AM

For: 123
While: 166
Foreach: 157
Lambda: 138

Hi, after i wonder why For is the slowest in your test i modify the test method. I think the most important thing about benchmarking is not to compare apple with pears.

    System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch();
    sw1.Start();
    var count = 10000000;
    for (var i = 0; i < count; i++) dummy = list[i];
    sw1.Stop();
    Console.WriteLine("For: " + sw1.ElapsedMilliseconds.ToString());
    dummy = null;

    System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
    sw2.Start();
    var enu = list.GetEnumerator();
    while (enu.MoveNext()) dummy = enu.Current;
    sw2.Stop();
    Console.WriteLine("While: " + sw2.ElapsedMilliseconds.ToString());
    dummy = null;

    System.Diagnostics.Stopwatch sw3 = new System.Diagnostics.Stopwatch();
    sw3.Start();
    foreach (var item in list) dummy = item;
    sw3.Stop();
    Console.WriteLine("Foreach: " + sw3.ElapsedMilliseconds.ToString());
    dummy = null;

    System.Diagnostics.Stopwatch sw4 = new System.Diagnostics.Stopwatch();
    sw4.Start();
    list.ForEach(s => dummy = s);
    sw4.Stop();
    Console.WriteLine("Lambda: " + sw4.ElapsedMilliseconds.ToString());

kind regards

Coordinator
Jan 25, 2010 at 11:29 AM

Just to make it clear: lowtekk made sure we don't do 10000000 calls to list.Count in the for-loop, thereby making it the fastest. 10000000 to the Count property is just plain stupid - in hindsight ;)

The example here wasn't actually meant to say that for-loops were slow, only to show off QuickBencher's features. And the thing is, many people would actually write for-loops the way I did in the sample, so thanks for this comment. I have previously heard - from MS sources I think - that foreach is supposed to perform better on lists than for-loops however, so now I'm a bit confused :)

This only goes to show how important doing benchmarks really is.. 

Jan 26, 2010 at 5:38 AM

You got me. QuickBencher is in my toolbox now.

With the help of QuickBencher its cleary to see that foreach is evil ^^ and much faster is the ForEach method. The test of

bm.Report("ForEach", () => { list.ForEach(delegate(string item) { dummy = item; }); });
gave this result:
                user     system      total        real
for         0.140401   0.000000   0.140401 (  0.128000)
while       0.140401   0.000000   0.140401 (  0.163000)
foreach     0.156001   0.000000   0.156001 (  0.160000)
ForEach     0.124801   0.000000   0.124801 (  0.113000)
lambda      0.124801   0.000000   0.124801 (  0.124000)
Thanks for provide QuickBencher!

Coordinator
Jan 26, 2010 at 10:52 AM

You're welcome! ;)

And stay tuned for updates.., there are some improvements planned that will come shortly.