背景:
阅读新闻

Useful Performance Tips For C#

[日期:2004-12-23] 来源:rob kennedy  作者: [字体: ]

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.

  1. Use finally in your try {} catch {} statements to ensure resource deallocation.
  2. Treat threads as a shared resource and use the optimized .NET thread pool when possible.
  3. Use the server garbage collector for server based multi-CPU environments.
  4. Avoid string concatenation with +=
  5. 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.
  6. Use thread pool when using threads.


    WaitCallback methTarget = new WaitCallback(myClass.Method);
    ThreadPool.QueueUserWorkItem(methTarget);

  7. Use StringBuilder for string concatenation; avoid using + to concatenate strings
  8. 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 }

  9. 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. :)

收藏 推荐 打印 | 录入:木鸟 | 阅读:
相关新闻      
本文评论   [发表评论]   全部评论 (0)
热门评论