简体   繁体   English

Java堆和堆栈内存分配

[英]Java heap and stack memory allocation

class Person{
          private String name;
          public Person(){
          }

          public Person(String name){
              this.name=name;
          }

          public static void main(String[] arg)
          {
                Person per= new Person("Andy");
          }
    }

per is a local variable, where will it be stored, on the heap or the stack? per是一个局部变量,它将被存储在堆还是堆栈中?

Objects are always stored in the heap . 对象始终存储在堆中 However, the reference to per will be stored in the local variable array , which is stored in the frame created for main(String[]) , which is stored in the stack . 但是,对per引用将存储在局部变量数组中 ,该数组存储在为main(String[])创建的中,该存储在堆栈中

For more information, see: The Structure of the Java Virtual Machine . 有关更多信息,请参阅: Java虚拟机的结构

Edit: I've learnt that JVMs are actually able to allocate objects on the stack by performing escape analysis . 编辑:我已经了解到JVM实际上能够通过执行转义分析来在堆栈上分配对象。 Better yet, a technique called scalar replacement can be applied, where the object allocation is omitted, and the object's fields are treated as local variables. 更好的是,可以应用一种称为标量替换的技术,其中省略了对象分配,并且对象的字段被视为局部变量。 It is possible for the variables to be allocated on machine registers. 变量可以在机器寄存器上分配。

Escape analysis by stack allocation has been implemented by HotSpot VMs since Java 6u14. 自Java 6u14以来,HotSpot VM已经实现了堆栈分配的逃逸分析。 It has been enabled by default since Java 6u23. 它自Java 6u23起默认启用。 For an object to be allocated on the stack, it must not escape the executing thread, the method body or be passed as an argument to another method. 对于要在堆栈上分配的对象,它不能转义执行的线程,方法体或作为参数传递给另一个方法。

On the heap. 在堆上。 Any time you use new to create an object, it is allocated on the heap. 每次使用new创建对象时,都会在堆上分配它。

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

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