zoukankan      html  css  js  c++  java
  • Useful Performance Tips for C#

    Useful Performance Tips for C#

     

     

    The following content are fully copied from Rob's blog. Thanks, Rob.

    Source URL: http://robkennedy.com/articles/146.aspx

     

    ***

    The following tips for C# are pretty useful to keep in mind while programming for future projects.

     

    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();

    // Creates a synchronized wrapper around the ArrayList.

    ArrayList mySyncedAr = ArrayList.Synchronized(myAr);

     

    // To use collection from thread:

    ArrayList myCollection = new ArrayList();

    lock(myCollection.SyncRoot);

    foreach ( Object item in myCollection )

    { // do work here }

     

    Please note the following remarks from MSDN:

    To guarantee the thread safety of the ArrayList, all operations must be done through this synchronized wrapper.

     

    Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

     

     

    9. Initialize collection sizes at startup to speed up node creation.

     

    Source URL:

    http://robkennedy.com/articles/146.aspx

     

    ***

    9条不怎么明白,是指如下2中情况吗?

    ArrayList myAL = new ArrayList(); // Without initializing collection sizes

    ArrayList myAL = new ArrayList(1000); // With initializing collection sizes

     

    那位帮忙解释一下,Thanks

  • 相关阅读:
    使用Python快速生成虚拟的超大文件
    常用的 adb 命令合集
    Jmeter 性能测试之反向代理录制性能测试脚本
    论医院网络时钟系统(NTP时钟服务器)的重要性
    北斗时钟装置(卫星时间同步系统)应用自动化系统探讨
    解决前端部署到Nginx非根目录下页面出现空白的问题
    解决docker中Easyexcel因缺少字体无法导出的问题
    看图认识HTML5
    看图知Docker
    ASIS CTF Finals 2020
  • 原文地址:https://www.cnblogs.com/rickie/p/67818.html
Copyright © 2011-2022 走看看