views:

88

answers:

1

Hello,

Suppose we have some class A that implements some interface I

I i = new A();
i.method(); // example 1
A a = (A)i;
a.method() // example 2

The IL code generated for each call to "method()" is same, but which one of invocations to method "method()" have more cost in native code and why?

Any help will be appreciated.

+1  A: 

Generally, the call to ((A)a).method() will be (ever so slightly) quicker, as the JIT compiler knows (statically) the concrete method that should be called, and so can call A.method directly. Calling it through the interface I requires a runtime check on the actual type of object that the reference points to, and then dispatch to that implementation. I don't have any references for that, though.

I do know that the Java JIT compiler has got some optimizations in this regard, as every method call is virtual - it guesses & caches the most-used implementation of a particular interface method and optimizes for that case. The .NET JIT doesn't need this nearly as much, as methods have to be explicitly virtual.

This is very much a case of micro-optimization that you really shouldn't be worrying about.

thecoop
That make sense, thanks.