rulururu

post Tipps for writing good performanced code in .NET

May 6th, 2008

Filed under: .NET, General Programming — Kai @ 5:50 pm

Writing code that runs quickly is sometimes at odds with writing code quickly.

Writing unnecessary code is undoubtedly bad for work efficiency. However, it’s important to realize that different situations have different needs. Code for vehicular real-time control systems has inherent up-front responsibilities for stability and performance that aren’t present in, say, a small one-off departmental application. Therefore, it’s more important in such code to optimize early and often.

  • 1. Tools
  • While testing tools such as NUnit and the upcoming VS.NET 2005 Team System can help you find bottlenecks, when tuning small sections of code, there’s still no substitute for the micro-benchmark. This is because most generic testing frameworks depend on things like delegates, attributes, and/or interface method calls to do testing, and the code usually is not written with benchmarking primarily in mind. This can be very significant if you’re interested in measuring the execution time of a batch of code down to the microsecond or even nanosecond level.
    However, these techniques alone can’t solve the dreaded problem of uniformly slow code, which surfaces when large bottlenecks have been resolved but the code still exhibits inadequate performance. This is code that has been written without attention to correct usage.

    Another important tool is ildasm.exe, the IL disassembler. With it, you can inspect the IL of your release builds to see if your assumptions are correct about what’s going on under the covers.
    A great free tool for decompiling IL to C# or VB source, Reflector, can be found [here]; it’s incredibly useful for viewing code that ships with the .NET Framework, for those of you less familiar with IL.

  • 2. Techniques & Guides Lines
  • 2.1 Objects and Garbage Collectors
    Objects are expensive to use, partly because of the overhead involved in allocating memory from the heap (which is actually well-optimized in .NET) and partly because every created object must eventually be destroyed. The destruction of an object may take longer than its creation and initialization, especially if the class contains a custom finalization routine.

    It’s necessary to understand garbage collection to appreciate the full impact of using objects. The single most important fact to know about the garbage collector is that it divides objects into three “generations”: 0, 1, and 2. Every object starts out in generation 0; if it survives (if at least one reference is maintained) long enough, it goes to 1; much later, it transitions to 2. The cost of collecting an object increases with each generation. For this reason, it’s important to avoid creating unnecessary objects, and to destroy each reference as quickly as possible. The objects that are left will often be long-lived and won’t be destroyed until application shutdown.

    2.2 Lazy Instantiation / Initialization
    The Singleton design pattern is often used to provide a single global instance of a class. Sometimes it’s the case that a particular singleton won’t be needed during an application run.
    It’s generally good practice to delay the creation of any object until it’s needed, unless there’s a specific need to the contrary - for instance, to pre-cache slow-initializing objects such as database connections. The “double-checked locking” pattern is useful in these situations, as a way to avoid synchronization and still ensure that a needed action is only performed once. Lazy initialization is a technique that can enhance the performance of an entire application through object reduction.

    2.3 Avoiding Useage of Class Destructors
    Class destructors cause extra overhead for the garbage collector, ’cause it must track which objects have been finalized before their memory can be reclaimed.

    2.4 Casting and Boxing / Unboxing Overhead
    Casting is the dynamic conversion of a type at runtime to another, and boxing is the creation of a reference wrapper for a value type (unboxing being the conversion back to the wrapped value type).
    The overhead of both is most heavily felt in collections classes, as they all - with the exception of certain specialized ones like StringDictionary - store each value as an Object. For instance, when you store an Int32 in an ArrayList, it is first boxed (wrapped in an object) when it is inserted; each time the value is read, it is unboxed before it is returned to the calling code.

    One soloution is to use generics, the other how to avoid overhead is to avoid it by creating strongly typed collections and by typing variables and parameters as strongly as possible. If you’re unsure about whether or not boxing/unboxing is taking place, you can check the IL of your code for appearances of the box and unbox keywords.

    2.5 Trusting the Garbage Collector
    Programmers new to .NET sometimes worry about memory allocation to the point that they explicitly invoke System.GC.Collect(). Garbage collection is a fairly expensive process, and it usually works best when left to its own devices. A thumb rule is not to call GC.Collect() unless you really know what you’re doing.

    2.6 Excessive use of Delegates
    Delegates are slower to execute than interface methods. Delegates are often used to introduce a level of indirection in code, but in almost all cases interfaces allow a cleaner design. Don’t use them if it’s not necessary.

    2.7 Using the ‘Sealed’ Keyword
    Wherever extensibility is not required, you should use the sealed keyword. This makes your design easier to understand, as someone can tell at a glance if a certain class or method isn’t meant to be extended or overridden. It also increases the chances that the compiler will inline code.

    2.8 for versus foreach
    The rumor abounds that the foreach loop is bad for performance. The truth is actually a little more complicated. Basically, foreach involves no performance penalty when used against arrays. However, when used against lists it involves the same overhead as creating an enumerator and using it within a try/catch block!

    2.8 Working With Strings
    Don’t Use String.Format() to Concatenate Strings.
    While string-formatting routines built into .NET are very useful for globalization and other tasks, they’re not meant to be used for appending strings to each other. You’d better prefer Stringbuilders as I explained in this post.

    2.9 Minimizing Synchronized Blocks
    The use of the [MethodImpl Attribute(MethodImplOptions.Synchronized)] attribute should be avoided, as it always locks an entire method and is also non-standard C# usage. Instead, the lock keyword or one of the System.Threading classes should be used. Wherever possible, adjust the start of a synchronized section forward and the end backward. Do whatever you can to decrease the number of synchronized operations.

    Do early optimization before rewriting half of your project afterwards but don’t waste too much time in optimizing parts of code that don’t make problems now. It’s never false thinking of writing a quick running code than just writing it down quick but don’t agonize over things that don’t make problems yet.

    1 Comment »

    1. […] roulette tipps wrote an interesting post today onHere’s a quick excerptWriting code that runs quickly is sometimes at odds with writing code quickly. Writing unnecessary code is undoubtedly bad for work efficiency. However, it’s important to realize that different situations have different needs. … […]

      Pingback by Tipps for writing good performanced code in .NET — May 7, 2008 @ 3:59 am

    RSS feed for comments on this post. TrackBack URI

    Leave a comment

    ruldrurd
    Powered by WordPress, Content and Design by Kai Bellmann
    Entries (RSS) and Comments (RSS)