I read a tweet today that said:
It\'s funny when Java users complain about type erasure, which is the only thing Java got right, while ignoring all th
Most answers are more concerned about programming philosophy than the actual technical details.
And although this question is more than 5 years old, the question still lingers: Why is type erasure desireable from a technical point of view? In the end, the answer is rather simple (on a higher level): https://en.wikipedia.org/wiki/Type_erasure
C++ templates don't exist at runtime. The compiler emits a fully optimized version for each invocation, meaning the execution doesn't depend on type information. But how does a JIT deal with different versions of the same function? Wouldn't it be better to just have one function? Wouldn't want the JIT to have to optimize all the different versions of it. Well, but then what about type safety? Guess that has to go out of the window.
But wait a second: How does .NET do it? Reflection! This way they only have to optimize one function and also get runtime type information. And that is why .NET generics used to be slower (though they have gotten much better). I am not arguing that that isn't convenient! But it is expensive and shouldn't be used when it isn't absolutely necessary (it isn't considered expensive in dynamically typed languages because the compiler / interpreter relies on reflection anyway).
This way generic programming with type erasure is close to zero overhead (some runtime checks / casts are still required): https://docs.oracle.com/javase/tutorial/java/generics/erasure.html