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

后端 未结 7 2105
故里飘歌
故里飘歌 2020-12-10 12:15

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

7条回答
  •  [愿得一人]
    2020-12-10 12:27

    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.

提交回复
热议问题