Even the best developers are always looking for ways to make their code faster and more efficient. Whether you’re brand new to C# or have been coding for a while, these tips can be useful to you to help optimize your code and make sure all your applications are lightweight and speedy.
1. Benchmark your code. When writing new methods, benchmarking your code using the stopwatch class can be really helpful in letting you know how efficient your code is. The stopwatch class can be used to tell you how long it takes for a method or function to be performed, and from there you can evaluate whether or not you’re happy with the speed of your code.
2. Avoid string based conversions — they’ll slow down your code a lot. If they can be avoided, any conversions that might create extra strings should be off-limits. These conversions (like .ToLower(), for example) are sometimes necessary, but it’s in the best interest of the speed of your app to try to find a way around using them.
3. Check for empty strings using string. Empty. Often in C#, you’ll see a line of code like this to check if a string is empty:
if (str == “")
While this line of code does work, it’s considered bad practice. Using string. Empty instead of the line of code above will enhance the performance of your code.
4. Use arrays. Lists are more commonly used in C#, but if you’re trying to store a large amount of data, using an array over a complex collection like a list can seriously enhance the speed of your code.
5. Finally: simplify your code. Go through your code with a fine-tooth comb and really take a look to see what might be unnecessary. Refactor and remove whatever you can do without. This can really lighten the load for your code.