Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java memory usage in inheritance

What does the memory usage look like in Java when extending a base class.

Do the child class contain an instance of the base class (with it's own overhead and all) or does it only have it's own overhead of 16 Bytes?

class Foo {
 int x;
}

class Bar extends Foo {
 int y;
}

So, more specifically, what is the memory usage of an instance of Bar?

Is it Foo (including overhead) + Bar(including overhead)

or just Foo (excluding overhead + Bar(including overhead)

like image 617
Linuxxon Avatar asked Sep 17 '14 12:09

Linuxxon


People also ask

How is memory allocated in inheritance?

In the above case the memory allocated will be which B class needs as B is inheriting from A, so when B is instantiated the base class which is class A constructor will also be called and memory will be allocated separately for both A and B class, and when you cast the instance of class B to A which is parent class of ...

How do I see Java memory usage?

Using VisualVM (jvisualvm) jvisualvm is a tool to analyse the runtime behavior of your Java application. It allows you to trace a running Java program and see its the memory and CPU consumption. You can also use it to create a memory heap dump to analyze the objects in the heap.

Does inheritance save space?

Conclusion: Inheritance in Programming A user can reuse its code once written and can save space and memory of code.


2 Answers

There is no double overhead.

Java will take the class, the superclasses, compute the space needed for all the fields, and allocate space needed for one single instance.

Form a memory point of view only, there does not exist the notion of superclass at all, there are instance of Foo that need memory for only one int, and instances of Bar that need memory for two ints, of which one is there because Bar happens to extend Foo.

So the overhead (or bookkeeping or whatever you want to call) happens only once.

However, when developing in java, is usually better not to care about memory stuff too much, unless you have very specific (and i mean very very very specific) use cases on which the bookkeping overhead is causing you serious problems. In that case, also the 8 byte padding should be considered.

Usually, there are many other ways you can improve the memory footprint of your application or it's overall performance, than not worrying about the memory overhead of each single instance.

like image 54
Simone Gianni Avatar answered Oct 13 '22 06:10

Simone Gianni


There is only one class header per object, so it has only the latter.

By the way, you can easily check this using https://sourceforge.net/projects/sizeof/ or https://code.google.com/p/memory-measurer/

like image 22
llogiq Avatar answered Oct 13 '22 07:10

llogiq