1

I'm wondering if the Java compiler will optimize the run of the for-loop if there no changes within the for-loop body?

For instance, let's suppose I have the following code:

double res = 0;
for (int i = 0; i < 1000; i++) {
    res = calculateResValue();
}

Will the compiler shortcut the for-loop into a single calculateResValue() call?

I tried to modify the upper bound of the iteration counter, and I noticed that the time spent within for loop doesn't change proportionally to the boundary increase, i.e. let's suppose I run the loop not for 1000 times but 10000 times. I expect the timing to be increased in 10 times, but it doesn't happen.

5
  • 7
    The compiler: no. The JIT: perhaps. Commented Oct 10, 2024 at 12:50
  • 3
    Suppose calculateResValue() modifies some external state. Would you want it to be optimized away? Commented Oct 10, 2024 at 13:00
  • @FedericoklezCulloca not really. Actually, I want it to show the fair time execution. I'm running code as a JUnit unit test, and I think it can use multithreading under the hood, so the real time of the execution could be compromised Commented Oct 10, 2024 at 13:23
  • My guess is that you are running into Loop Invariant Code Motion. In this case, if a calculation within a loop doesn't change with each iteration, the compiler might move it outside. Have a look at the AI Overview -> type java for loop compiler optimization into Google. Commented Oct 10, 2024 at 14:50
  • 6
    "single calculateResValue() call" - the method must be called that many times, the (javac) compiler does not really know what the method is doing (or it does not analyze it) - it cannot decide if calling once will be a good replacement for all calls (the developer should know that ... ) Also check this question and its answer: How do I write a correct micro-benchmark in Java? Commented Oct 10, 2024 at 14:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.