问题描述
在Java中,声明数组后如何检查分配给数组的字节数?例如:
In Java, how the check number of bytes allocated to an array after it's declaration?For example:
int[] a = new int[10];
数组'a'被分配4 * 10字节,因为int的大小为4字节,并且有10个整数元素.有非手动的方式吗?
Array 'a' is allocated 4*10 bytes since the size of int is 4 bytes and there are 10 integer elements. Is there a non-manual way of doing this?
推荐答案
实际上 int [10]
的大小为56个字节或更多(取决于JVM).
Actually the size of int[10]
is 56 bytes or more (depending on your JVM).
- 10 * 4 = 40个字节(十个整数)
- 4个字节来存储数组长度 Java对象
- 8个字节
- 4个字节以使对象的大小为8(对齐)的倍数.
但这全部取决于您的操作系统的JVM和内存体系结构. java.lang.instrumentation.Instrumentation
提供了一种计算对象大小的方法,如此答案.
But this all depends on the JVM and memory architecture of your operating system. java.lang.instrumentation.Instrumentation
provides a way to calculate sizes of an object, as explained in this answer.
这篇关于在Java中进行声明后分配给数组的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!