java 基本数据类型各种情况下在内存中存储位置?
黄舟
黄舟 2017-04-18 10:52:21
0
4
537

问题:

如何理解《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:存储在堆中

如果是存储在堆中的话,何来高效一说?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

Antworte allen(4)
PHPzhong

我们不能一概而论的说,基本类型数据都是放在栈中的!当某个 类实例 中具有基本类型时,基本类型就放在堆中!

Ty80

内存分为堆和栈,这你已经知道了。

堆内存是属于JVM的,栈内存是属于方法的,方法结束了,栈内存也就没了。

程序运行main函数时,有一个堆内存,一个main的栈内存

int var3 = 0;
这个var3,是放在main函数的栈内存中的,是一个值。

之后
demo obj1 = new demo();
main函数的栈内存中有了一个引用变量,obj1,指向了堆内存中new出来的这个实例。

我们再看堆内存中的这个实例,他有2个字段,他们都是存放在堆中的。

等到main函数运行结束时,假如还有别的线程在运行,JVM还没有结束,此时,main函数的栈内存被清除,var3,不在了,obj1这个引用变量也不在了,但是堆内存中的那个实例依然在,如果没有别的引用变量 指向它 ,那么它将在稍后被清除。

巴扎黑

是翻译错误,原文中用的是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.

巴扎黑

p22,堆栈指的是stack,堆指的是heap

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!