Java common interface performance
A simple question, but I guess it's a tricky answer
Does using a common interface compromise performance?
Example:
public interface Stuff<T> { void hello(T var); } vs public interface Stuff { void hello(Integer var); <---- Integer used just as an example }
My first thought was that it didn't Generics are only part of the language, and the compiler optimizes it as if there were no generics (at least in the special case of a generic interface)
Is it correct?
Solution
Since the compiler sometimes adds synthetic bridging methods, there may be a slight performance loss Consider the following example:
public class GenericPerformance { public static void main(final String[] args) { final Stuff<Integer> stuff = new IntStuff(); final Integer data = stuff.getData(); stuff.putData(data); } } interface Stuff<T> { T getData(); void putData(T stuff); } class IntStuff implements Stuff<Integer> { private Integer stuff; public Integer getData() { return stuff; } public void putData(final Integer stuff) { this.stuff = stuff; } }
If you look at the generated bytecode, you will see that in the main method, the interface method is erased
java.lang.Object Stuff.getData() void Stuff.putData(java.lang.Object)
Called That method is implemented with signature in intstuff
java.lang.Object getData() void putData(java.lang.Object)
Both are synthesized with modifiers and public bridges, delegated to "real" methods
java.lang.Integer IntStuff.getData() void putData(java.lang.Integer)
The first synthesis method only returns integer results, while the second synthesis method performs the conversion from object to integer before calling putdata (integer)
If you change the stuff variable to intstuff type, two integer methods are called instead of the composite object method