0

Does loop unrolling works for loops where iteration count is determined during runtime? E.g. will the inner loop will be considered for unrolling in this code:

for(int j = 0; j < HUGE_NUMBER; j++) {
  int N = getCount(); // say N = 5
  for(int i = 0; i < N; i++) {
    doSomething(i);
  }
}

Does loop unrolling works differently in Scala? Will the JIT compiler treat the following code snippets the same way?

// Java
int N = getCount();
for(int i = 0; i < N; i++) {
  doSomething(i);
}

// Scala
val N = getCount();
var i = 0
while(i < N) {
  doSomething(i);
  i+=1
}
synapse
  • 5,588
  • 6
  • 35
  • 65
  • 2
    I would expect the vast majority of loops would have the iteration count determined at runtime (think all loops across ArrayLists, etc), so I'm sure those would be capable of being unrolled - probably after the JIT compiler has seen them run through a few times and so can estimate how best to handle each case. – racraman Jul 15 '19 at 05:31
  • Probably of interest https://stackoverflow.com/questions/7243221/java-jit-loop-unrolling-policy https://softwareengineering.stackexchange.com/questions/285041/does-loop-unrolling-on-a-jit-platfrom-net-or-jvm-provide-any-benefit – Thilo Jul 15 '19 at 09:50

1 Answers1

0

The JIT compiler works on the Java bytecode so the unroll behaviour is independent of the original language and will depend on the particular JVM/compiler that is being used.

I don't believe that the Scala compiler implements its own loop unrolling. It is quite rare to use this kind of counting loop in Scala so it is probably not worth optimising it.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • If I wanted to look at the bytecode I wouldn't have posted this question. The `while` loop is way faster than alternatives for any kind of number-crunching, so it's a way to go if you don't want to create a `.java` file in your project. – synapse Jul 24 '19 at 00:58
  • You are exaggerating the benefits of both while loops and unrolling. The benefits apply to only a small proportion of number-crunching algorithms. If there is any divergence or complex computation the benefits disappear and it can start to hurt performance. – Tim Jul 24 '19 at 06:33