Wednesday, April 4, 2007

Generics - .Net Vs Java

All of you would have heard about the new feature called “Generics” that has been introduced both in .Net CLR for Whidbey as well as Java 1.5. Given below is a small comparison between the Generics in both these technologies with respect to their role in improving performance.

What is Generics?

“Generics” is a means of creating parameterized objects, i.e. specifying the objects that a class can work with at the time of declaring the objects. These objects are then evaluated at the compile time itself unlike at the run time as is the case without Generics.

While .Net Generics offers a performance boost to the program, Generics in Java is mainly intended to improve code clarity and readability.

The advantages offered by Generics in Java are:

1) Improved code readability
2) Reduced casts.

However, it is important to note that since casting is still being performed behind the scenes, the Java programs will not receive a performance boost from using generics. The addition of generics to the Java language is not intended to improve performance; it is intended to increase program readability and reliability while maintaining backwards compatibility with existing programs.

How is Generics in .Net different from that of Java?

Generics in .NET offer all of the advantages mentioned for them in the Java world, but unlike the Java world, in the .NET world we do find potential performance gains mentioned as an advantage of using .NET generics. Technically, the reason appears to be that the Java implementation is based in the Java compiler which simply generates an ordinary collection wrapped with type casting, just as we would use without generics to build a type-safe collection. But in .NET generics are implemented within the CLR, so that the code itself is type safe and type-casting is eliminated. In other words, generic variables (as opposed to java) don't need any casts at all as they are stored in the specific type. So if there is a generic list of ints it is internally handled as a real int-array and not as an array of objects which get cast to Integer and then unboxed. Thus the expected performance gains.

Current benchmarks of a quick-sort of an array of one million integers shows that the generic method is three times faster than the non-generic equivalent. This is because boxing of the values is avoided completely. The same sort over an array of string references resulted in a 20 percent improvement in performance with the generic method due to the absence of a need to perform type checking at run time.

The following links give more information on what generics are:

http://research.microsoft.com/projects/clrgen/generics.pdf

http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

No comments: