简体   繁体   English

Java 2d数组的大小

[英]Size of 2d array in Java

I defined a 2d array in Java. 我用Java定义了一个二维数组。 As I read about it(ie 2d array), the first dimension of this 2d array is a pointer (I do not know that is it right or not, please tell me about it). 当我读到它(即2d数组)时,这个2d数组的第一个维度是一个指针(我不知道它是否正确,请告诉我)。 So If I consider it as pointer, in a 64-bit system, what will be the size of below code after execution? 因此,如果我将其视为指针,在64位系统中,执行后以下代码的大小是多少?

    short [][] array1 = new short [10][];
    short[][] array2 = new short[10][];
    for (int i = 0; i < 10; i++)
        array1[i] = new short[1];
    for (int i = 0; i < 10; i++)            
            array2[i] = array1[i];         

Please tell me about the size of above code. 请告诉我上述代码的大小。

For every one dimensional array you have a 24 byte overhead in addition to the space for the data in the array. 对于每个一维数组,除了数组中数据的空间外,您还有24字节的开销。

  • So your first two lines of code each create an array of 10 pointers - you are right about that - which take 8 bytes each on 64-bit system. 因此,您的前两行代码分别创建了一个包含10个指针的数组-对此您是正确的-在64位系统上,每个指针占用8个字节。 This means you are allocating 2 * (24 + 10 * 8) = 208 bytes. 这意味着您正在分配2 *(24 + 10 * 8)= 208个字节。
  • In the first for loop you are creating 10 arrays which are 24 + 2 * 10 = 44 bytes each. 在第一个for循环中,您将创建10个数组,每个数组均为24 + 2 * 10 = 44字节。 These are padded to at least 8 byte boundaries and thus take up 48 bytes or 480 bytes in total. 这些被填充到至少8个字节的边界,因此总共占用48个字节或480个字节。
  • In the second loop, you are not allocating any new memory. 在第二个循环中,您没有分配任何新的内存。
  • In total you are using 208 + 480 = 688 bytes. 总共使用的是208 + 480 = 688字节。

Note that the actual usage depends on the JVM. 请注意,实际用法取决于JVM。 For example: 例如:

  • Some JVMs compress pointers . 一些JVM 压缩指针
  • Some JVMs only use a 12 byte header for arrays. 一些JVM仅将12个字节的标头用于数组。

In order to see the difference between outer and inner arrays it might be helpful to rewrite your code like this: 为了查看外部数组和内部数组之间的差异,像这样重写代码可能会有所帮助:

short[][] outerArray = new short[10][]; // Array of references to short arrays
short[] innerArray;                     // Array of shorts
for (int i = 0; i < 10; i++) {
  innerArray = new short[1];
  outerArray[i] = innerArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM