Coding Tips & Tricks


Home > C#

Measuring the Performance of Built-in .Net Classes

I've always wondered which built-in .Net classes are faster compared to others. There is a lot of conventional wisdom surrounding certain code classes in .Net and which ones are better to use than others. One thing that I always try and keep in mind when writing code is that different situations have different needs. As I am always keen to learn more about my trade, I decided to write some simple performance tests to see how these different classes compare against one another. Once I got into writing them, I decided to test more and more built in .net operations.

First off, I wrote a simple class using the .Net Stopwatch Class that would measure and record the time that each operation took to complete. I found this to be a great exercise to learn about these .Net operations and also how to write better, more efficient code.

measure performance

Firstly, I started off by comparing the For Loop and the Do While Loop. The two methods below just add a incremented string to a generic list. This is the code I used:

While Loop vs. For Loop

        /// <summary>

        /// Loops through the list until it

        /// reaches a count of 3000.

        /// </summary>

        public void WhileLoop()

        {

            List<string> list = new List<string>();

           

            int x = 0;

            do

            {

                list.Add("Test" + x);

                x++;

            } while (x < 3000);

        }

Then the For Loop:

        /// <summary>

        /// Loops through the loop until it reaches a count of 3000

        /// </summary>

        public void ForLoop()

        {

            List<string> list = new List<string>();

 

            for (int i = 0; i < 3000; i++)

            {

                list.Add("Test" + i);

            }

        }

Now surprisingly, the while loop was faster in every circumstance that I ran it. I ran them both in different orders, and I also varied the size of the object that I was testing with. I also understand that this is a very simple way of testing, but it basically proves the performance for each of these methods. So far I found this pretty interesting, so next why not test a lambda expression versus a two different kinds of loops. Basically, I wanted to find the quickest way to search through a list.

Lambda Expression vs. ForEach Loop vs. For Loop

Using a Lambda Expression:

            populatedList.Find(x => x == "Test2500");

Using a ForEach Loop:

            foreach (string findString in populatedList)

            {

                if (findString == "Test2500")

                {

                    return;

                }

            }

Using  a For Loop:

            for (int i = 0; i < ListLoop.Count; i++)

            {

                if (populatedList[i] == "Test2500")

                {

                    return;

                }

            }

Test Results

So this time, I found a definite difference in speed. The Lambda expression was a lot faster than looping through the list until I found what I wanted. Surprisingly though, using a for loop was quite significantly slower than the Lambda expression. Now I know the difference between these times is very small, but when you use these a lot in an application any small gain in performance can increase exponentially.

HashSet<T> vs. List<T>

For the next test, I wanted to test the performance of HashSet versus a Generic List. I kinda already knew that a HashSet would be faster because it has been built for high performance operations, but I wanted to see how much faster.

Hash Results

Surprisingly, when I had a small amount of records in my object that I was searching I only really received a small difference between the two. But, when I upped the records from 3000 to 13,000 and then searched through the records I noticed a definite difference. The HashSet was taking 0.0003ms to return results as opposed to the List which took about 0.2148ms. That's quite a difference!

Conclusion

One thing to bear in mind that there are a lot of factors involved in performance testing something like this, and also times and speed will vary from machine to machine. However, I can draw an overall conclusion based on the facts that these tests proved time and time again that certain classes were faster than the other. I am using Visual Studio 2008 and NUnit to run these tests.

So to finalize what I observed:

  • A While Loop is slightly faster than a For Loop when adding to a list.
  • A HashSet is a lot faster than a Generic List (Although it is not always applicable to use a hashset)
  • Using a Lambda expression is a lot faster than searching through a Generic List using a loop.

Also, for more information on Lambda expressions take a look at my other post that I wrote.
If anyone has any suggestions or techniques that they prefer to use then please give me a shout.








Comments

Aaron - 4/21/2010
Interesting!

Tim Acheson - 4/22/2010
Mr Hume, thanks for producing yet another bite-sized, useful and original article. I love knowing facts like these! Loops are used so ubiquitously, it's healthy to focus in on them like this sometimes to ensure we're striking the best balance between performance and readability/maintainability.

Lex - 6/8/2010
Nice little article man; I would however mention that you should be cautious with microbenchmarks, Rico summed it up quite nicely http://blogs.msdn.com/b/ricom/archive/2010/04/26/a-few-words-about-micro-benchmarks.aspx Also check the performance wizard (especially if you have VS2010) its slick

Dean - 6/9/2010
@Lex Nice one, thanks I will definitely check that out!

beulah nelson - 9/21/2010
Is it possible to use Lamda with hashset


Add your comment

300 Characters left


Please fill this in to confirm that you are human