Hacker News new | ask | show | jobs
by frankzinger 3142 days ago
It sounds like you're saying Java's generics are somehow superior to C++ templates.

For those who don't know, C++ generates a separate instance of the code for each type which means that it can operate directly on a value instead of through a reference/pointer and it also makes it possible for the compiler to inline the type-specific code in many cases. Ie., it has the potential to be much more efficient. That is why it works the way it does. The downside is that the code generation slows down compile times, as you noted.

Java simply casts a reference to an instance of Object to the type on behalf of the user. So you effectively have generic code the way it's done in C (void*) and Go (interface{}) but without the explicit casts.

Maybe the JIT offsets many of these inefficiencies but making that comparison is beyond me. I only bring this up because you made it sound like Java got generics completely right and C++ got it all wrong, and with the amount of flak C++ gets these days I think it deserves a little help now and then.

1 comments

I didn't intend it to come across like that. C++ is how you have to do aggressive type specialisations and optimisations in the absence of a JITC. Java's JITC is able to do many of the same things at runtime as C++ does at compile time, but it's less predictable.