gpt4 book ai didi

java - 空循环比java中的非空循环消耗更多的内存

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:23 24 4
gpt4 key购买 nike

我正在阅读有关 Java 性能调优的文章并遇到了这个问题。

当我们运行时

public class test {
public static void main(String a[]){
for(int i=0;i<1000000;i++){
for(int j=0;j<100000;j++){
Double d = new Double(1.0);
}
}
}
}

JVisualVM 显示了内存消耗图表:

enter image description here

但是当我们运行下面的代码时,

public class test {
public static void main(String a[]){
for(int i=0;i<1000000;i++){
for(int j=0;j<100000;j++){
}
}
}
}

JVisualVM 呈现锯齿波:

enter image description here

为什么会这样?对于这两种情况,如何以及为什么更改 gc 触发限制?

最佳答案

关于你的 v1 for loops,你的局部变量,一旦它退出它的范围,它将被标记为 GC 可以自由收集,所以每隔一段时间 GC 就会启动并收集那段内存。

对于您的 v2 for 循环,那些空循环不会被编译器“优化掉”**,只有在多次调用之后,因为

JIT triggers AFTER a certain piece of code has been executed many times [1]

关于您的锯齿图案,ruakh对此有一个很好的解释 [2] :

If I'm not mistaken, part of the reason for this is that the monitor itself is forcing the application to create temporary objects that contain information about the state of garbage-collection and memory usage.

** 它们可能永远不会被删除,因为众所周知,这些空循环被用作等待机制。*

[1] Java: how much time does an empty loop use? - Simone Gianni's answer

[2] Why does an empty Java program consume memory?

关于java - 空循环比java中的非空循环消耗更多的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25402947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com