Friday, August 12, 2016

MethodImplOptions.AggressiveInlining - When Performance is Critical (1)

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.

Thursday, August 4, 2016

A New Multi-Tenancy Framework for Building Software-as-a-Service (SaaS)

The goal of this project is to provide the framework needed to build multi-tenant .NET applications while using your preferred choice of ORM (NHibernate, EntityFramework, Dapper etc), IoC Container (SimpleInjector, AutoFac, StructureMap, Unity, etc) and web frameworks (MVC, NancyFx). We provide the basic and generic functions needed in typical SaaS solutions, like authentication, authorization, custom URL, data separation etc., thus freeing you up to focus solely on building your product.

The diagram below shows the framework architecture and will help in understanding how things (ought to) connect to each other.
Architecture Diagram for MultiTenancyFramework



A full documentation is provided through the project's Wiki page and by downloading the sample projects provided.

The source code is hosted on Github