Editorials

Increasing Dot Net Code Performance

Recently I have been thinking about different things I have done to optimize Dot Net code over the last few years and trying to come up with some of the top performers. Here are two big performance optimizations.

  1. Materialize Dot Net Linq expressions. When you perform Linq expressions resulting in values that will be enumerated (pretty much anytime) be sure to materialize the final output using ToList(), ToArray() or some other collection type. This one item alone can have a big impact on your application performance if you use a lot of Linq queries in your application.
  2. Remove conditional statements that are enclosed in looping syntax if possible. If you are going to use a function every time you go through a loop, you reduce the amount of work if any switch or if statement may be resolved prior to the loop.

    For example, consider a user configurable feature where they can determine different rounding scenarios to be used against final results from some computation. If you perform that computation multiple times in a loop you can optimize your code by selecting a method to perform the rounding once before entering the loop. In this fashion the rounding formula is selected only one time regardless of the number of iterations in the loop.

    You can use a number of different techniques to allow the selection of the rounding formula prior to loop execution rather than embedding it in a loop with a switch or series of if statements. A strategy pattern or delegate implementation works very well. A delegate with Lambda expressions is probably the most flexible to write without class sprawl.

What’s your top optimization tip? Share your experience by leaving comments here, or drop an email to btaylor@sswug.org.

Cheers,

Ben