Extension methods

Rémi Forax forax at univ-mlv.fr
Fri Nov 20 17:34:45 PST 2009


Le 21/11/2009 00:52, Neal Gafter a écrit :
> On Fri, Nov 20, 2009 at 3:30 PM, Rémi Forax <forax at univ-mlv.fr 
> <mailto:forax at univ-mlv.fr>> wrote:
>
>     There is a real problem of performance with extension methods
>     (at least with Hotspot).
>     Extension methods create megamorphic call sites
>     and Hotspot is not able to inline them.
>
>
> Extension methods are most simply formulated are static methods (as in 
> C#), and are therefore not polymorphic at runtime at all.  They can 
> even be inlined trivially.  Such a formulation enables existing 
> methods (such as those in Collections and Arrays) to be retrofitted as 
> extension methods as well.

The problem is not at call site of the extension method but call sites 
in the extension method.

>
> Perhaps you have another technique in mind for extension methods?


There is another reason why I don't like extension methods is that
you can't override an extension method so you install fences for the future.

Lets me take an example, suppose you introduce an extension method
to do a foreach using a closure on Collection. You can't override this 
method
to write a specialized version for TreeSet.

The fundamental problem is that you can't add new methods to an interface.
What I porpose is to define

There is already an existing mechanism to insert extension methods
at runtime: interface injection
(http://openjdk.java.net/projects/mlvm/subprojects.html#InterfaceInjection)

This mechanism allow to add an interface + implementation to a class at 
runtime.

Written in Java, it will be something like that:
package java.util;
public extension interface ExtMap<K,V> extends Map<K,V> {
   public Map.entry getEntry(K key) {
     ...
   }
}

package java.util;
public interface Map<K,V> extension ExtMap<K,V> {
   ...
}

You need a slight transformation of the code if you don't want to
change the verifier:

And this Java code:
Map<String, String> map = ...
Entry<String, String> entry = map.getEntry("hello");

will be translated to:
Map<String, String> map = ...
Entry<String, String> entry = ((ExtMap)map).getEntry("hello");

cheers,
Rémi





More information about the coin-dev mailing list