Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 'Date' object size [closed]

Tags:

java

date

memory

How to effectively determine the size of a Date object in my memory?

Initially I went through this link which talks about 9 bytes for a date object..

I was trying to find it out when I found this link, where it talks about 32 bytes!!!! for a date object in memory.

Date Object Size in Memory

Kindly help.

Reason for thinking on these lines: I am loading millions of objects of a certain class into memory, for some computation. One of the variables in that class is a Date object. I can store the value as a long, but that would require minor quirks in the code. I am thinking on keeping the memory footprint to the least value possible. To do that, I need to know the exact memory requirements in each case to take a call on the same.

like image 399
LPD Avatar asked Sep 01 '14 06:09

LPD


2 Answers

Your first link is talking about the size when serialized, you're talking about the size in memory. That's why the sizes are different.

Serialized, as per your link, 9 bytes for the saved long.

In memory, as per your second link, 32 bytes for the long and other objects that allow you to work with the date.

like image 57
Evan Knowles Avatar answered Oct 27 '22 01:10

Evan Knowles


Easiest way to answer this question is to look at the source code of java.util.Date.

It has only 2 non-static fields (Java 1.7.0_55):

private transient long fastTime;
private transient BaseCalendar.Date cdate;

long has a memory size of 8 bytes and cdate is an object reference which has a size of 4 bytes. So a total of 12 bytes.

If cdate would be instantiated, it could require additional bytes in the memory, but if you look at the constructors too, sometimes it won't even be touched, and in others it will be null-ed at the end of the constructor, so the final result is also 12 bytes.

This is just for creating a Date. If you call methods on the Date (for example Date.toString()), that will create and store an object into the cdate field which will not be cleared. So if you call certain methods on the Date, its memory usage will increase.

Note: Object references might be 64 bit long on 64-bit JVMs in which case memory usage would be 16 bytes.

Note #2: Also note that this is just the memory usage of the Date object itself. Most likely you will store its reference somewhere, e.g. in an array or list or a field in some other class which will require additional 4 bytes (or maybe 8 bytes on 64 bit JVMs).

like image 40
icza Avatar answered Oct 27 '22 01:10

icza