C# Programming > Miscellaneous

C# Test Performance
Methods and Algorithms

 

C# Code Performance

Programming C# offers so much flexibility sometimes it is necessary to test the performance of methods and other algorithms to select the fastest most efficient method.

Especially when optimizing C# code, it is important to compare changes that help or hurt performance. Testing source code speed is easy enough because the .NET Framework offers the very accurate StopWatch class.

Note that this article builds upon the previous Code Speed Testing Utility.

How to Test Speed

In most cases computers run C# methods so fast that it is impossible to tell the difference in speed between two methods. The way to get around that is to make the computer run the same method over and over. A high number of trials makes it possible to compare the running time algorithms.

However you can read all about that in the Code Speed Testing article. What's new is how we are going to handle the testing procedure to minimize the number of times we write the same thing over and over. What we need is a class that let's you pass it a method as a parameter and handles all the testing procedure automatically.

How to Use the Code

The class can be downloaded at the bottom of the page. Let's talk for a second about how to use it. The initializer works like this:

SpeedTester myTest = new SpeedTester([method to test]);
myTest.RunTest();

Notice how convinient it is to pass an entire method as a parameter. But there is a catch, the method passed but be a void method with no parameters. So how would you test a C# method that takes a string as a parameter and returns in integer for example?

Simple, write a wrapper method. For example:

private void myWrapperCall()
{
     int i = myMethod("some-long-string-to-test-for-speed-and-efficiency");
}

Then the SpeedTester class would run on myWrapperCall. This flexibility let's you decide how you want a method to be called during the performance test and what data it will work on.

Additionally features are the RunTest method runs 10,000 trials by default, but has an overload call to let you specify exactly how many trials to run. After running the test, properties TotalRunningTime and AverageRunningTime give the appropriate running times in milliseconds so you can compare the C# code performance.

Back to C# Article List