如何理解《Java编程思想-第四版》P23 中,这个变量直接存储“值”,并置于堆栈中,因此更加高效
一句中的 “堆栈” 两字,到底是堆还是栈?情况如下:
class demo {
private int var1; // 字段1
private Integer var2; // 字段2
public static void main(String[] args) {
int var3 = 0; // 变量1
demo obj1 = new demo(); // 实例1
}
}
参考《Java编程思想-第四版》P23 和 《深入理解Java虚拟机:JVM高级特性与最佳实践 第2版》P39-P43,对于该 demo
实例1:存储在堆内存中
变量1:存储在方法栈中
实例1中的字段1:存储在堆中
实例1中的字段2:存储在堆中
如果是存储在堆中的话,何来高效一说?
PHPz2017-04-18 10:54:21
We cannot generalize and say that all basic types of data are placed on the stack! When a class instance has a primitive type, the primitive type is placed on the heap!
PHP中文网2017-04-18 10:54:21
Memory is divided into heap and stack, you already know this.
The heap memory belongs to the JVM, and the stack memory belongs to the method. When the method ends, the stack memory is gone.
When the program runs the main function, there is a heap memory and a main stack memory
int var3 = 0;
This var3 is placed in the stack memory of the main function and is a value.
After
demo obj1 = new demo();
There is a reference variable in the stack memory of the main function, obj1, pointing to the new instance in the heap memory.
Let’s look at this instance in the heap memory again. It has 2 fields, both of which are stored in the heap.
When the main function ends, if there are other threads running, the JVM has not yet ended. At this time, the stack memory of the main function is cleared, var3 is no longer there, and the reference variable obj1 is no longer there, but in the heap memory The instance of is still there, and if no other reference variable points to it, it will be cleared later.
巴扎黑2017-04-18 10:54:21
是翻译错误,原文中用的是stack,即栈,而不是堆栈。以下是原文:
Special case: primitive types
One group of types, which you’ll use quite often in your programming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap. For these types Java falls back on the approach taken by C and C++. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and it’s placed on the stack, so it’s much more efficient.