Speeding Up C#

This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:

  • Firstly : Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?

  • Secondly : When writing a program from scratch in C#, what are some good ways to greatly improve performance?

  • Please stay away from general optimization techniques unless they are C# specific.

    This has previously been asked for Python, Perl, and Java.


    Off the top of my head:

  • Replace non-generic variants of container classes by their generic counterparts
  • Cut down on boxing/unboxing. Specifically, use generics where possible and generally avoid passing value types as object .
  • For dialogs using many dynamic controls: suspend drawing until after inserting all controls by using SuspendLayout / ResumeLayout . This helps especially when using layout containers.

  • Unfortunately, relatively few optimisations are language specific. The basics apply across languages:

  • Measure performance against realistic loads
  • Have clearly-defined goals to guide you
  • Use a good profiler
  • Optimise architecture/design relatively early
  • Only micro-optimise when you've got a proven problem
  • When you've absolutely proved you need to micro-optimise, the profiler tends to make it obvious what to look for - things like avoiding boxing and virtual calls.

    Oh, one thing I can think of which is .NET-specific: if you need to make a call frequently and are currently using reflection, convert those calls into delegates.

    EDIT: The other answers suggesting using generics and StringBuilder etc are of course correct. I (probably wrongly) assumed that those optimisations were too "obvious" ;)


    One simple thing is to ensure that your build configuration is set to "Release". This will enable optimizations and eliminate debugging information, making your executable smaller.

    More info on MSDN if needed.

    链接地址: http://www.djcxy.com/p/39594.html

    上一篇: Tensorflow:同时预测GPU和CPU

    下一篇: 加速C#