I was reading MSDN the other day and came across some performance tips that I thought were pretty useful to keep in mind while programming for future projects. Below are the tips that I thought were useful and would be nice to share with others.
- Use finally in your try {} catch {} statements to ensure resource deallocation.
- Treat threads as a shared resource and use the optimized .NET thread pool when possible.
- Use the server garbage collector for server based multi-CPU environments.
- Avoid string concatenation with +=
- Use the using(obj) short hand to simplify coding. using() is the same as try{}finally{obj.Dispose(); } and insures that obj is disposed of after use.
- Use thread pool when using threads.
WaitCallback methTarget = new WaitCallback(myClass.Method);
ThreadPool.QueueUserWorkItem(methTarget);
- Use StringBuilder for string concatenation; avoid using + to concatenate strings
- If interacting with collections from multiple threads, you must make the collection thread safe.
ArrayList myAr = new ArrayList();
ArrayList mySyncedAr = ArrayList.Synchronized(myAr);
// To use collection from thread:
lock(myCollection.SyncRoot);
{ // do work here }
- Initialize collection sizes at startup to speed up node creation
Well I hope that helps some of you. I know I'll write more efficient code using these rules. :)
