It seems like optimization is a lost art these days. Wasn't there a time when all programmers squeezed every ounce of efficiency from their code? Often doing so while walking 5 miles in the snow?
In the spirit of bringing back a lost art, what are some tips that you know of for simple (or perhaps complex) changes to optimize C#/.NET code? Since it's such a broad thing that depends on what one is trying to accomplish it'd help to provide context with your tip. For instance:
- When concatenating many strings together use
StringBuilder
instead. See link at the bottom for caveats on this. - Use
string.Compare
to compare 2 strings instead of doing something likestring1.ToLower() == string2.ToLower()
The general consensus so far seems to be measuring is key. This kind of misses the point: measuring doesn't tell you what's wrong, or what to do about it if you run into a bottle neck. I ran into the string concatenation bottle neck once and had no idea what to do about it, so these tips are useful.
My point for even posting this is to have a place for common bottle necks and how they can be avoided before even running into them. It's not even necessarily about plug and play code that anyone should blindly follow, but more about gaining an understanding that performance should be thought about, at least somewhat, and that there's some common pitfalls to look out for.
I can see though that it might be useful to also know why a tip is useful and where it should be applied. For the StringBuilder
tip I found the help I did long ago at here on Jon Skeet's site.