-2

This is an interview question: There is a custom PERSON object which have some properties like name, age, gender, etc. Write a generic function which can return the size of this object. It should not use any direct API of Java to get the size of Object. This object can have int, float, char or any custom type also like address.

Sonam
  • 572
  • 4
  • 13
  • How about returning the sum of all the sizes of the class? – Turtle May 05 '17 at 12:32
  • [This answer might help you](http://stackoverflow.com/a/52682/3143670) – Neeraj Jain May 05 '17 at 12:32
  • 1
    That's not a good question (check [ask]), but then again, I'm actually interested in answers. What I don't really get is what *"should not use any direct API of Java"* means exactly. – domsson May 05 '17 at 12:37
  • @NeerajJain I believe he can't use that. That's probably what he meant by "not use any direct API" – Turtle May 05 '17 at 12:39
  • Direct API means do not use available functions in Java like Instrumentation or some other funtions. – Sonam May 05 '17 at 12:40
  • @Nathan: I was also thinking the same. I think we can get the solution by getting the type of variable by instaceOf operator and then adding the memory required by different types like int, float, etc. Correct me if I am wrong? – Sonam May 05 '17 at 12:44
  • 1
    I feel like this question is a bit of a trap. Of course you can add up the sizes of all the primitive members; remember to take array sizes into account. But what about member objects? What if `Person` extends another class that adds other members? Also, all of this is not dynamic at all. Plus, just because we know an `int` is 32 bit in Java doesn't guarantee that the JVM/OS will actually use 32 bits to store it. Also, `instanceOf()` doesn't work for primitive types directly. There are so many pitfalls, so many things to consider... I'm not sure a clean solution is actually possible here. – domsson May 05 '17 at 12:50
  • Related: http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java – domsson May 05 '17 at 12:56
  • What's your actual question? – EJoshuaS - Stand with Ukraine May 05 '17 at 13:09
  • @Sonam Exactly. You can check my answer, I referenced an easy way to do it. – Turtle May 05 '17 at 13:13

1 Answers1

1

In java, the size of an object can be said to be really close to the sum of the size of its members (except static ones).

Note that if you're using java8, the primitive wrappers have a field Bytes public static that represents the size of the primitive in bytes.

Source : http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

If you're not using Java8, you can use some of these:

  • anObject.getClass().isPrimitive();
  • anObject.getClass().getFields();
  • recursion.

You should also be careful of bytes alignement, aka placing a 7-bytes-long elements on 8-bit segments, but this will depend of your JVM and is more of an hardware question.

Turtle
  • 1,626
  • 16
  • 26