是否为了在多维数组的声明对使用的内存的影响? [英] Does order in a declaration of multidimensional array have an influence on used memory?

查看:148
本文介绍了是否为了在多维数组的声明对使用的内存的影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有多少个字节将为分配 A B

How many bytes will be allocated for a and b?

import android.graphics.Bitmap;

Bitmap[][][] a = new Bitmap[1000][2][2];
Bitmap[][][] b = new Bitmap[2][2][1000];

请注意,我只问纯数组里面,没有对象采取的内存。

Note that I'm only asking about the memory taken by pure arrays, no objects inside.

<子>为什么我问的?因为我在写一个Android游戏。对我来说,顺序并不重要,但如果是有记忆的差异,这将是很好的节省一些。

推荐答案

是它确实有所作为。

在Java中,二维数组是一维数组的数组和数组(像所有的对象)有头除了持有元素本身所需要的空间。

In Java, a 2D array is an array of 1D arrays, and arrays (like all objects) have headers in addition to the space needed to hold the elements themselves.

因此​​,考虑 INT [10] [2] INT [2] [10] ,并承担32位JVM。

So consider int[10][2] versus int[2][10], and assume a 32 bit JVM.


  • INT [2] [10] 由2元和2个阵列10个元素的一个阵列中。总计 - 3数组对象+ 22元

  • INT [10] [2] 包含10个元素,和2元件10阵列中的一个阵列。合计 - 11数组对象+ 30元

  • int[2][10] consists of one array of 2 elements, and 2 arrays of 10 elements. Total - 3 array objects + 22 elements.
  • int[10][2] consists of one array of 10 elements, and 10 arrays of 2 elements. Total - 11 array objects + 30 elements.

如果我们假设报头大小是3个32位字(典型为32位,JVM)和基准为1的32位字,然后

If we assume that the header size is 3 32-bit words (typical for a 32bit JVM) and a reference is 1 32-bit word, then


  • INT [2] [10] 需要3 * 3 + 22 *​​ 1 = 31个字= 124字节

  • INT [10] [2] 需要11 * 3 + 30 * 1 = 63个字= 252字节

  • int[2][10] takes 3*3 + 22*1 = 31 words = 124 bytes
  • int[10][2] takes 11*3 + 30*1 = 63 words = 252 bytes

应用相同的逻辑,你可以用维数较高的估计数组的大小。

Apply the same logic and you can estimate the size of arrays with higher numbers of dimensions.

但是很显然,使用如最大尺寸是最右边的少了一个空间。

But it is clear that you use less space if the largest dimension is the right-most one.

<子>我已经做了数学与 INT 阵列,但在32位机器上的 INT 参考占用相同的字节数。在64位机,引用可以是大小相同的 INT ,取决于JVM选项。头部的大小也可以是不同的....不完全相信......可能依赖于平台。

I've done the math with int arrays, but on a 32 bit machine an int and a reference occupy the same number of bytes. On a 64 bit machine, a reference can be the same size as an int or a long, depending on JVM options. The header sizes may also be different .... not exactly sure ... potentially platform dependent.

<子>我没有占持有所需的空间的位图对象本身,却是无论你如何组织阵列相同的。

I've not accounted for the space required to hold the Bitmap objects themselves, but it is the same however you organize the arrays.

这篇关于是否为了在多维数组的声明对使用的内存的影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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