The development of a Java VM for .NET
Anders Hejlsberg came up with a clever trick to implement generic algorithms with the current C# generics implementation.
According to the C# Version 2.0 Language Specification, interface method invocations on value types (uses a generics parameters) will not cause the value to be boxed. This gave me the idea to use a value type for the calculator to avoid the virtual function dispatch.
using System; using System.Collections.Generic; interface ICalculator<T> { T Add(T t1, T t2); } struct IntCalculator : ICalculator<int> { public int Add(int t1, int t2) { return t1 + t2; } } class AlgorithmLibrary<C, T> where C : ICalculator<T> { static C calculator = C.default;
public static T Sum(List<T> items) { T sum = T.default; for(int i = 0; i < items.Count; i++) { sum = calculator.Add(sum, items[i]); } return sum; } }
public class Class4 { static void Main() { List<int> foo = new List <int>(); foo.Add(1); foo.Add(2); foo.Add(3); int sum = AlgorithmLibrary<IntCalculator, int>.Sum(foo); Console.WriteLine(sum); } }
Depending on how the JIT decides to compile this, this could be very efficient (the JIT could decide to generate specialized x86 code for every type that Sum() is used on).
Remember Me
I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.
Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)