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?
解决方案
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.