Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bytes of memory does a java.util.Date object use?

Tags:

java

date

memory

I need to store a large amount of dates (potentially large enough that the amount of heap space used is a concern so please, no lectures on premature optimization), and I'm wondering if it makes sense to use some sort of primitive representation instead of java.util.Date (or some other existing Date class). I know I could do some profiling to try it out, but does anyone know off-hand exactly how many bytes of memory a single Date object uses?

like image 709
Michael McGowan Avatar asked Jan 13 '11 15:01

Michael McGowan


People also ask

How much memory does a Java object take?

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes.

How much memory does a byte take in Java?

byte is a primitive data type similar to int, except it only takes up 8 bits of memory. This is why we call it a byte. Because the memory size is so small, byte can only hold the values from -128 (-27) to 127 (27 – 1).

How many bytes is a Java object?

Objects, References and Wrapper Classes. Minimum object size is 16 bytes for modern 64-bit JDK since the object has 12-byte header, padded to a multiple of 8 bytes.

Does Java Util date store time?

Conclusion. Class java. util. Date stores a date-time value as milliseconds since the epoch.


2 Answers

My gut reaction was that the memory overhead for Date would be very small. Examining the source code it seems that the class only contains one instance field (a long called milliseconds). Which means the size of a date object is the size of a long plus the size of an instance of Object -- that is, very small.

I then found this code that creates thousands of objects to determine the size of the object. It says that the size of java.util.Date is 32 bytes. Compare that with just storing a the date as a long (which is what it does internally) -- a long is 8 bytes, so you have to pay four fold for the convenience of having a date object.

However, the overhead of creating of objects isn't very high. So if you're really that worried about space then store the dates as longs and create a Date object as and when needed.

like image 198
Dunes Avatar answered Oct 01 '22 02:10

Dunes


Use the primitive long ?

It is not an object, so less space, and dates can be expressed as a long value. Then convert back and forth between Date and long when you want to store the dates and use less memory.

like image 26
rapadura Avatar answered Oct 01 '22 03:10

rapadura