4 ms·
It's not about inheritance, it's about how to implement composition. In C++, B inheriting A is implemented to same as B containing a member variable of type A a
by johncolanduoni 10y ago
It's not about inheritance, it's about how to implement composition. In C++, B inheriting A is implemented to same as B containing a member variable of type A as far as memory layout: the form one allocation with space for A's fields as well as B. In Java or .NET, fields which are objects are pointers to a separate allocation, like they would be if they were pointed to in C++, even if you assign them once and never change them. This increases indirection, memory and GC overhead, and reduces locality. Since you can nest containment, the effect from this can be quite large. .NET has structs to offset this a bit, but they make you decide for each type instead of each variable and you can't really operate on references to them.
Obviously there are cases where you need that indirection (e.g if you're swapping out pointers to different objects in that field) but there are plenty cases where you don't (this usage pattern is a big part of the reason why write barriers work okay for these languages). Also note that you don't need to use indirection if all you want to do is use/store a garbage collected pointer to the field's object elsewhere in your program; the .NET garbage collector already has the ability to deal with pointers within allocations. It's just that they've stuck to not discriminating between these within the language for simplicity (IIRC the .NET runtime can sort of use interior pointers to structs, but this isn't exposed in C#).