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?
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.
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).
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.
Conclusion. Class java. util. Date stores a date-time value as milliseconds since the epoch.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With