1

IF I have an interface In1 and two classes c1,c2 which implement In1
And if i have two classes x1,x2 which just have their own methods
which behave the same way as c1,c2 like:

In1  i1 = new c1();
i1 = new c2();

and

X1 x1 = new x1();
X2 x2 = new x2();

Which of the above consumes more memory ?

Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44

1 Answers1

4

Assuming the implementations are otherwise identical, whether or not the classes implement interface(s) will not significantly alter runtime memory requirements.

Looking specifically at your code

In1  i1 = new c1();
i1 = new c2();

and

X1 x1 = new x1();
X2 x2 = new x2();

In the first block, your instance of c1 is no longer referenced once i1 = new c2() is run. That makes it eligible for garbage collection. That code block is not the same as the second code block, because the second code block maintains a reference to both allocated objects.

However, if you rewrite your first code block as

In1  i1a = new c1();
In1  i1b = new c2();

your memory requirements are again exactly the same with or without interfaces, because you hold a reference to the objects for the same duration.

UPDATE

If you mark methods of your class final, I believe you will save slightly on memory allocation due to the fact that a vtable is not needed. Methods declared in interfaces cannot be marked final.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • There will probably be some minor memory increase on the side of the `Class` object for the class implementing an interface. – Jiri Tousek Jan 21 '16 at 19:59
  • @JiriTousek: I suspect that interface implementation is managed entirely at compile time. If a method in the class were marked final, that would reduce the memory footprint a bit because it would remove the need for a vtable. However, final methods cannot be used with interfaces. I'll update my answer to reflect that. – Eric J. Jan 21 '16 at 20:04
  • Interface implementetion is retained at runtime. If it wasn't, the runtime could not check a runtime cast like `MyInterface bar = (MyInterface) foo`, and you couldn't use [`Class.getInterfaces()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getInterfaces--) and [`Class.isAssignableFrom()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-). – Jiri Tousek Jan 21 '16 at 20:37
  • @JiriTousek: I don't think that is overhead per instance though, just information associated with the type. Sure it has to be stored but it's likely just a few extra bytes, once. – Eric J. Jan 21 '16 at 20:47
  • Agreed, see my first comment: "minor memory increase on the side of `Class` object ...". Likely a few bytes of constant overhead not growing with number of instances, but you can't call it "exactly the same". – Jiri Tousek Jan 21 '16 at 21:40