Can JIT do this field access optimization?

Disclaimer: No advice on premature optimization. I'm just curious.

Imagine that I want to make sure that some of the objects referenced by the field can be collected as garbage. I use my own single list like this

class BigData { byte[] someBigArray; BigData next; } private BigData bigData; 

and repeat the same

 while (bigData != null) { process(bigData); bigData = bigData.next; } 

Can I change the JIT as follows?

 BigData tmp = bigData; while (tmp != null) { process(tmp); tmp = tmp.next; } bigData = null; 

Suppose there is no other reference to any instance of BigData . Suppose process is a simple built-in method that does not access the BigData field. Both fragments are equivalent (provided that an exception is not thrown between them), the only difference is that the second moves the access to the field from the loop to the outside.

Disclaimer repeated: do not consult premature optimization. I'm just curious.


To respond to the comment β€œEven if the change you need” is what JIT does, why would the GC do it faster / earlier? ": If the JIT makes this change, then all large objects can be collected only after the cycle. If it is not, then every time the cycle moves forward, another object becomes suitable for the GC.

Addendum:

Actually, whenever a JIT is free to do the above conversion, it can do this instead:

 BigData tmp = bigData; bigData = null; while (tmp != null) { process(tmp); tmp = tmp.next; } 

I see no flaw here, and it makes all items collectable as soon as in the source code.

+4
java optimization garbage-collection jit
source share
1 answer

Well, the optimizer can optimize

 while (bigData != null) { process(bigData); bigData = bigData.next; } 

in

 BigData tmp = bigData; while (tmp != null) { process(tmp); tmp = tmp.next; } bigData = null; 

if the bigData field bigData not volatile , and the process method has no side effects that prohibit this optimization.

But in practice, code conversion, if any, will look completely different. Typically, optimizers do a loop reversal, creating a block of code that performs a certain number of iterations, and perform a storage operation on the ground before making a jump back. Thus, there are certain β€œsavepoints” that the garbage collector may enter. But if the process method contains code that accesses the bigData field or can allocate memory, etc., the Field Storage will be executed before each call.

+2
source share

All Articles