parallax circle item parallax circle item parallax circle item
Insights & Blogs

5 ways to write faster C#

Code on computer screen

Much of my time is spent working on Sandfield’s Crossfire EDI engine.  It is essentially a program similar to Biztalk, which convert files between different formats (e.g. CSV to XML)

Some customers do over over 50,000 conversions in just a working day, so we need to run frequent performance tests to ensure the code is running optimally.

We use a tool called ANTS Performance Profiler, from Redgate which is excellent at identifying slow running functions.  Here are 5 easy ways to make your C# application run faster.

1. Use XmlNodeReader over XPath

The XmlNodeReader and XmlTextReader will perform significantly faster than using any XPath expression. It obviously has some limitations, but executed in almost half the time when we made this optimisation.

Slow

line of computer code


Fast

line of computer code

2. Use String.Compare instead of =’s

When doing a case-insensitive compare, the String.Compare function provides far greater performance than using the equals operator and two case modifying functions.

Slow

line of computer code


Fast

line of computer code

3. Avoid many calls to Guid.NewGuid()

A GUID is a very easy way to give an object a unique id, so you would be tempted to use it, but this takes significantly longer than simply assigning a sequential counter.


Slow

line of computer code


Fast

lines of computer code

4. Use For instead of ForEach

Using a for loop when not using collections can be up to twice as fast as running the same loop using foreach.


Slow

lines of computer code

Fast

lines of computer code

There is a great explanation on the differences between for and foreach loops here.

5. Use Release Mode

Something every developer should be doing anyway, our live installations in release mode perform about 20% faster than in debug mode on the same machine.

Hopefully, you find a use for at least one of these in your applications.   Happy developing.

profile picture of Henry Payne
Posted by Henry Payne

Henry Payne leads the Crossfire team of tech and business experts. His depth of experience has been built over the past 13 years with the company, working with customers across the globe; from medium-sized businesses to publicly-listed companies with billions of revenue.
When not integrating systems, Henry can be found spending time with his family and a range of outdoor pursuits including sea fishing, snow skiing and cycling.

Follow us for the latest insights

Related Articles