使用堆栈空间的Java数组
这是声明Java数组的常用方法:
int[] arr = new int[100];
但是这个数组正在使用堆空间。 有没有办法我们可以使用像c ++这样的堆栈空间声明一个数组?
总之,没有。
存储在堆栈中的唯一变量是基元和对象引用。 在您的示例中, arr
引用存储在堆栈中,但它引用堆上的数据。
如果你问这个问题来自C ++,因为你想确保清理你的内存,请阅读垃圾收集 。 简而言之,Java会自动负责清理堆中的内存以及堆栈中的内存。
Arrays are objects
,无论它是保存原始类型还是对象类型,因此与任何其他对象一样,它allocated space on the heap.
But then from Java 6u23
版本开始, Escape Analysis
就出现了, default activated in Java 7
。
Escape Analysis is about the scope of the object
, when an object is defined inside a method scope rather than a class scope
Escape Analysis is about the scope of the object
when an object is defined inside a method scope rather than a class scope
,JVM知道该对象无法逃避此有限的方法范围,并对其应用各种优化。如常量折叠等等
Then it can also allocate the object which is defined in the method scope, on the Thread's Stack, which is accessing the method.
数组是动态分配的,因此它们会在堆上运行。
我的意思是,当你这样做时会发生什么:
int[] arr = new int[4]; arr = new int[5];
如果第一次分配是在堆栈上完成的,我们将如何进行垃圾收集呢? 引用arr
存储在堆栈中,但实际的数据数组必须在堆上。
它还不支持作为语言function,因为这需要值类型,因为通过引用传递堆栈数据是不安全的。
但是作为优化( 转义分析 ),JVM可能已经为包含小的固定大小数组的局部变量执行了此操作,前提是它可以certificate它不会逃避本地/被调用范围。 也就是说,它只是一个运行时优化,而不是一些规范保证,所以依赖它很困难。