Search code examples
c#performancegarbage-collectionunmanagedmanaged

In managed code, what should I look after to keep good performance?


I am originally a native C++ programmer, in C++ every process in your program is bound to your code, i.e, nothing happens unless you want it to happen. And every bit of memory is allocated (and deallocated) according to what you wrote. So, performance is all your responsibility, if you do good, you get great performance.

(Note: Please don't complain about the code one haven't written himself such as STL, it's a C++ unmanaged code after all, that is the significant part).

But in managed code, such as code in Java and C#, you don't control every process, and memory is "hidden", or not under your control, to some extent. And that makes performance something relatively unknown, mostly you fear bad performance.

So my question is: What issues and Bold Lines should I look after and keep in mind to achieve a good performance in managed code?

I could think only of some practices such as:

  • Being aware of boxing and unboxing.
  • Choosing the correct Collection that best suites your needs and has the lowest operation cost.

But these never seem to be enough and even convincing! In fact perhaps I shouldn't have mentioned them.

Please note I am not asking for a C++ VS C# (or Java) code comparing, I just mentioned C++ to explain the problem.


Solution

  • There is no single answer here. The only way to answer this is: profile. Measure early and often. The bottlenecks are usually not where you expect them. Optimize the things that actually hurt. We use mvc-mini-profiler for this, but any similar tool will work.

    You seem to be focusing on GC; now, that can sometimes be an issue, but usually only in specific cases; for the majority of systems the generational GC works great.

    Obviously external resources will be slow; caching may be critical: in odd scenarios with very-long-lived data there are tricks you can do with structs to avoid long GEN-2 collects; serialization (files, network, etc), materialization (ORM), or just bad collection/algorithn choice may be the biggest issue - you cannot know until you measure.


    Two things though:

    • make sure you understand what IDisposable and "using" mean
    • don't concatenate strings in loops; mass concatenation is the job of StringBuilder