8

If I have an interface:

 interface IMyInterface
 {
    void DoSomething();
 }

And an implementing class:

 class MyClass : IMyInterface
 {
     public void DoSomething()
     {

     }
 }

Is DoSomething a candidate for inlining? I'd expect "no" because if it's an interface then the object may be cast as a IMyInterface, so the actual method being called is unknown. But then the fact that it's not marked as virtual implies it may not be on the vtable, so if the object is cast as MyClass, then maybe it could be inlined?

STLDev
  • 5,950
  • 25
  • 36
Victor Chelaru
  • 4,491
  • 3
  • 35
  • 49
  • Do you mean "Will the Microsoft C# compiler inline method calls on interface methods?" or "Will the Microsoft C# compiler inline method calls on methods that implement interfaces?" To be honest, the easiest way to figure it out is to compile something and check out the IL. – Aron Feb 25 '14 at 06:00
  • Here is a example.. May be useful to you http://stackoverflow.com/a/4900181/3156647 – tarzanbappa Feb 25 '14 at 06:02
  • @Aron - I'm asking about #2, as I am 99% sure the answer to #1 is that no, it will not inline. Also, inlining is something that sometimes happens and sometimes doesn't, so I may write up an example which doesn't inline, but the method may still be categorized as a possible inline-able method. – Victor Chelaru Feb 25 '14 at 06:07
  • 2
    @tarzanbappa erh? I don't think he is asking about Lambdas. I believe he is asking about the compiler optimisation, whereby the compiler, instead of inserting a function call in the code (resulting in several indirections), instead just inserts the code for the function instead. – Aron Feb 25 '14 at 06:10
  • 7
    @Aron Actually the C# compiler will never do inlining. It is the JIT compiler that does inlining. – Mike Zboray Feb 25 '14 at 07:34

1 Answers1

9

If you call DoSomething directly then it will be a candidate for inlining (depending on whether the method meets the other inlining criteria relating to size etc).

If you call DoSomething via the interface then it will not be inlined. The indirection provided by the interface results in a virtual call requiring a vtable lookup so the JIT compiler is unable to inline it since the actual callsite is only resolved at runtime.

0b101010
  • 756
  • 6
  • 15