Java类VS数组的内存大小? [英] Java class vs array memory size?

查看:185
本文介绍了Java类VS数组的内存大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储数百万的X / Y双对在我的Java程序的参考。我想保持内存的消耗尽可能低以及对象引用的数量。所以经过一番思考,我决定在一个很小的双阵列拿着两个点可能是一个好主意,它的设置看起来像这样:

I have to store millions of X/Y double pairs for reference in my Java program. I'd like to keep memory consumption as low as possible as well as the number of object references. So after some thinking I decided holding the two points in a tiny double array might be a good idea, it's setup looks like so:

double[] node = new double[2];
node[0] = x;
node[1] = y;

我想用数组将prevent在一个类中使用的类和我的X和Y变量之间的关系,如下所示:

I figured using the array would prevent the link between the class and my X and Y variables used in a class, as follows:

class Node {
     public double x, y;
}

然而,在类的公共字段存储读入的方式后,我恍然大悟,表格中实际上可能没有构造为状结构的指针,也许JVM只是存储在连续内存中这些价值和知道如何找到它们而不这样一个地址让我的观点比数组较小的类重presentation。

However after reading into the way public fields in classes are stored, it dawned on me that fields may not actually be structured as pointer like structures, perhaps the JVM is simply storing these values in contiguous memory and knows how to find them without an address thus making the class representation of my point smaller than the array.

所以现在的问题是,它有一个更小的内存占用?为什么?

So the question is, which has a smaller memory footprint? And why?

我在类字段是否使用指针特别感兴趣,因而有32位的开销,还是不行。

I'm particularly interested in whether or not class fields use a pointer, and thus have a 32-bit overhead, or not.

推荐答案

后者有更小的空间。

基本类型的内嵌存储在包含类。所以,你的节点需要一个对象头和两个64位插槽。您指定的阵列使用一个阵列头(> =对象头)plust两个64位插槽。

Primitive types are stored inline in the containing class. So your Node requires one object header and two 64-bit slots. The array you specify uses one array header (>= an object header) plust two 64-bit slots.

如果你要分配这样100个变量,那么它不那么重要了,因为它只是头大小而不同。

If you're going to allocate 100 variables this way, then it doesn't matter so much, as it is just the header sizes which are different.

告诫:这一切是有点投机因为你没有指定JVM - 其中的一些细节可能有所不同JVM

Caveat: all of this is somewhat speculative as you did not specify the JVM - some of these details may vary by JVM.

这篇关于Java类VS数组的内存大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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