java 数组 内存,Java类VS数组的内存大小?

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;

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;

}

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?

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

解决方案

The latter has the smaller footprint.

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.

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值