java.util.Date对象使用多少个内存字节? [英] How many bytes of memory does a java.util.Date object use?

查看:1848
本文介绍了java.util.Date对象使用多少个内存字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储大量的日期(可能足够大,使用的堆空间的数量是一个问题,所以请不要过早优化的讲座),我想知道使用某种而不是java.util.Date(或其他一些现有的Date类)的原始表示。我知道我可以做一些分析来尝试一下,但是有没有人知道一个Date对象使用的内存有多少字节?

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?

推荐答案

我的反应是Date的内存开销很小。检查源代码似乎该类只包含一个实例字段(长称为毫秒)。这意味着日期对象的大小是一个长的大小加上一个实例的大小,这是非常小的。

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.

然后我发现此代码创建了数千个对象来确定对象的大小。它表示 java.util.Date 的大小是32字节。相比之下,只要将日期存储为一个长(这是它内部的内容) - 一个长度是8个字节,所以你必须支付四倍以方便有一个日期对象。

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.

但是,创建对象的开销不是很高。所以,如果你真的担心空间,那么将日期存储为longs,并在需要时创建一个Date对象。

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.

这篇关于java.util.Date对象使用多少个内存字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆