The Is, As and the Is-As
04/25/2018
C# has recently introduced with C# 7 a couple of new syntax sugars. I this post, I will investigate the new is keyword from IL standpoint and from performance standpoint. I will investigate by analyzing the generated IL Code and by micro benchmarking the instructions.
In my tests I repeat and measure the time it takes to run these instructions in a loop of 1000000000. I elimininate the best and worst case, and calculate an average on the rest.
The book Pro .Net Performance has a chapter on micro benchmarking the is and as keywords. It starts with a false assumption that the 'as' keyword is faster compared to the 'is', while the real conclusion of the chapter would be to consider all details of micro benchmarking to avoid making false assumption.I will have a simple 'My' class created for the tests. Note, the NoInlining attribute on the Work method to avoid any optimization when invoking the method.
public class My { public int a = 0; [MethodImpl(MethodImplOptions.NoInlining)] public void Work() {} }