Background
As a C# (.NET) developer, I'm constantly being reminded that it's more important to prioritize code maintainability over performance optimizations. The argument is usually that most optimizations we do is usually premature and therefore unnecessary.But recently I began working on a C# implementation of an algorithm for network motif discovery and all those good programming principles failed me. The first implementation was not only consuming too much memory (over 2GB withing 2 minutes of execution), it was taking too long (over 5 hours for my E. Coli test network) to execute. That was totally unacceptable, so I knew it was time to put Performance where it belongs - the first place.
In this series, I will be sharing some of the more interesting optimizations I did to bring my program to execute within milliseconds with very little memory footprint. This particular piece is dedicated to Method Inlining.
Method Inlining
Method calls come at a cost. This cost can usually be avoided by inlining - writing the code directly instead of factoring it into a method. However, methods make our codes more readable and maintainable. Besides, this so-called cost is totally insignificant in a vast majority of program requirements. In some cases, the compiler does the inlining for you too.However, from .NET 4.5 Microsoft provided us a means to explicitly ask the compiler to inline a method. That means we can still write our codes normally and simply instruct the compiler to inline it. It's achieved by adding the following attribute to the concerned method.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
You'll need to add the following using statement:
using System.Runtime.CompilerServices;
I added this on a few of the methods that are frequently called and my program execution became twice as fast. However, it doesn't seem to work as well on extension methods.
Try it out and let me know your experience.
No comments:
Post a Comment
Let's hear from you