Monday, March 05, 2007

Optimizing code using a stop watch

NET 2 has a stop watch, which sometimes comes in handy when it comes to identifying slow code and optimizing performance. The StopWatch object can be found under the System.Diagnostics namespace and contains methods Start() and Stop().

In order to identify the time spent on excecuting a method, you could try something like this:

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();


WriteToScreen("Time spent: " + watch.Elapsed.ToString());

For instance, you can use this method to measure if you gain from creating indexes in your database layer or the time spent on sorting lists etc.