在内存中保留最大整数数组所需的空间 [英] Space required to keep largest integer array in memory

查看:50
本文介绍了在内存中保留最大整数数组所需的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查一种算法,它保留一个整数数组,输入的大小是动态的.因此,根据我的计算,它最多可能需要花费

I am reviewing an algorithm and it keeps an array of integers, the size of input is dynamic. So according to my calculations it can take as much as

  integer MAX_VALUE  * int size  = ?   
      2^31 integers  * 4 bytes   = ?
2147483648 integers  * 4 bytes   = 8 Gigabytes

此计算正确吗?JVM会使用这么多连续的空间来存储int数组还是还有其他需要考虑的事情?

Is this calculation correct ? would the JVM use this much contiguous space to store the int array or are there other things that one needs to consider ?

推荐答案

数组的理论大小为:

  • numberOfElementsInTheArray * 4个字节

  • numberOfElementsInTheArray * 4 bytes

12个字节的标头( int [] 是一个对象).实际上,标头的大小取决于您使用的标志以及JVM版本上的您正在运行此

12 bytes of headers (int[] is an Object). Actually the size of headers depends on the flags you used and on the JVM version you are running this

4个字节以保持数组的 length 长度

4 bytes to keep the length of the array

填充.

例如:(我将为此使用 JOL ):

For example: (I am going to use JOL for this):

    int [] x = new int[10];
    for(int i=0;i<10;++i){
        x[i] = 9999;
    }
    System.out.println(GraphLayout.parseInstance((Object)x).toPrintable()); 

将输出:

 [I@7a81197dd object externals:
      ADDRESS       SIZE TYPE PATH                           VALUE
    70fe45268         56 [I                                  [9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999]

所以它有 56个字节:

  • 值本身为40(10个整数* 4个字节)
  • 12个标题
  • 4个长度
  • 0填充

如果将此数组更改为 Integer ,则情况将发生巨大变化. Integer 是一个对象,因此您将在数组内部存储一个引用(可以是 4 8 字节,具体取决于 UseCompressedOops 标志),再加上每个 Integer 实例将需要2个标头(每个 Integer 是一个对象).

If you change this array to Integer, things change dramatically. Integer is an Object so you will store a reference inside the array (which could be 4 or 8 bytes, depending on UseCompressedOops flag), plus each of the Integer instances will require 2 headers (each Integer is an Object).

    Integer[] y = new Integer[10];
    for(int i=0;i<10;++i){
        y[i] = 9999;
    }

    System.out.println(GraphLayout.parseInstance((Object)y).toFootprint());

将显示:

   [Ljava.lang.Integer;@369f73a2d footprint:
 COUNT       AVG       SUM   DESCRIPTION
     1        56        56   [Ljava.lang.Integer;
    10        16       160   java.lang.Integer
    11                 216   (total)

总共 216字节:

    每个引用
  • 4个字节(我已打开 UseCompressedOop ),总共40个字节
  • 该数组的12个字节的标头
  • 数组的4个字节长
  • 0字节填充
  • 4 bytes for each reference (I have UseCompressedOop turned on), 40 bytes total
  • 12 bytes headers of the array
  • 4 bytes length of the array
  • 0 bytes padding

该数组中的每个引用都指向一个 Integer ,每个对象将具有 16个字节:

Each reference from that array points to an Integer, each of those Objects will have 16 bytes:

  • 内部保存的 int 的4个字节
  • 12个字节的标头
  • 0字节填充

这篇关于在内存中保留最大整数数组所需的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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