Hacker News new | past | comments | ask | show | jobs | submit login

Why would type erasure hurt performance? Certainly expressiveness is curtailed due to Java's generics design (or lack thereof), but I wasn't aware of any performance implications.



Whenever a generic class method returns an erased type and the caller tries to use it, javac has to insert a runtime check (cast) so the bytecode is typesafe. It also forces boxing of primitive types.


But since the type of a function can't change at runtime, why is this necessary?


Because of erasure, there is only one copy of List#get(int), and it returns Object (because there's no other upper bound). The source might say

  List<String> l = ...
  String s = l.get(0);
which looks typesafe, but to pass the verifier and load, the bytecode has to accept an Object and cast it to String before using it, just like Java programmers had to write by hand before generics (this really sucked).

There's not even anything stopping you from putting non-Strings in that List instance via reflection or generic casts (if you ignore the warning) or using a really old javac. You could use a checked collection but that just adds a runtime check during writes that ensures the runtime check during reads will never fail (but the bytecode verifier still won't let you remove it!)


I should have written ArrayList#get. It's possible to write a class that implements List<String> in a typesafe way, but callers using the standard List interface receive an Object and have to downcast.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: