Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C# inline methods that are declared in interfaces?

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?

like image 259
Victor Chelaru Avatar asked Feb 25 '14 05:02

Victor Chelaru


1 Answers

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.

like image 94
0b101010 Avatar answered Sep 30 '22 16:09

0b101010