简体   繁体   English

在 java 中声明后分配给数组的字节数

[英]Number of bytes allocated to an array after it's declaration in java

In Java, how the check number of bytes allocated to an array after it's declaration?在 Java 中,如何检查声明后分配给数组的字节数? For example:例如:

 int[] a = new int[10];

Array 'a' is allocated 4*10 bytes since the size of int is 4 bytes and there are 10 integer elements.数组“a”分配了 4*10 字节,因为 int 的大小为 4 字节,并且有 10 个 integer 元素。 Is there a non-manual way of doing this?有没有一种非手动的方式来做到这一点?

In Java there is no operator like sizeof in C to get the size of the array element.在 Java 中没有像 C 中的sizeof这样的运算符来获取数组元素的大小。 So there is at least no straightforward way.所以至少没有直接的方法。

By the way, no memory is allocated during declaration, only during initialization.顺便说一句,在声明期间没有分配 memory,仅在初始化期间分配。

Declaration:宣言:

 int[] a;

Initialization:初始化:

 a = new int[10];

Actually the size of int[10] is 56 bytes or more (depending on your JVM).实际上int[10]的大小是 56 字节或更多(取决于您的 JVM)。

  • 10 * 4 = 40 bytes for the ten ints 10 * 4 = 10 个整数的 40 个字节
  • 4 bytes to store the array length 4字节存储数组长度
  • 8 bytes for the Java object Java object 为 8 个字节
  • 4 bytes to make the size of the object a multiple of 8 (alignment). 4 个字节使 object 的大小成为 8 的倍数(对齐)。

But this all depends on the JVM and memory architecture of your operating system.但这一切都取决于您的操作系统的 JVM 和 memory 架构。 java.lang.instrumentation.Instrumentation provides a way to calculate sizes of an object, as explained in this answer . java.lang.instrumentation.Instrumentation提供了一种计算 object 大小的方法,如本答案中所述。

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

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