An empty loop consumes more memory than a non empty loop in java

I read about tuning Java performance and came across this.

When we run

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 displays a graph of memory consumption:

enter image description here

But when we run the code below,

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

JVisualVM displays a sawtooth shape:

enter image description here

Why is this happening? How and why does the gc launch restriction change for both cases?

+6
source share
2 answers

As for your v1 for loops , your local variable, as soon as it leaves its area, it will be marked as a GC that can be collected, so from time to time the GC will start and collect this memory.

For your v2 for loops these empty loops will not be "optimized" by the compiler **, only after several calls, because

JIT triggers AFTER a specific piece of code is executed once [1]

Regarding the tooth tooth pattern, ruakh has a very good explanation about this [2]:

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

** They may never be removed, as these empty loops are well known as used as a wait mechanism. *

[1] Java: how long does an empty loop use? - Reply of Simone Gianni

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

+2
source

The reason is the optimization algorithm after compiling the code. in the first case, because you create a double every time without writing it. This will force the program to use the GC constantly. Thus, the compiler optimizes the code, so less memory is used. An empty loop is a special case because many programmers use it to make a thread wait. therefore, the compiler will not try to optimize this.

+1
source

Source: https://habr.com/ru/post/974088/


All Articles