I noticed in my benchmarks that arithmetic compound operators in Java always outperform the regular assignment:
d0 *= d0; //faster
//d0 = d0 * d0; //slower
d0 += d0; //faster
//d0 = d0 + d0; //slower
Could someone please comment on the above observation and explain why it is the case. I'm assuming that some differences on the bytecode level are responsible for the speedup? Thank you in advance.
Here's my benchmark, more fully:
public long squaring() {
long t0 = System.currentTimeMillis();
double d0 = 0;
for (int k = 0; k < 100_000_000; k++){
//check bytecode for below to see why timing differs
d0 *= d0; //faster
//d0 = d0 * d0; //slower
}
long t1 = System.currentTimeMillis();
long took = (t1 - t0);
System.out.println("took: "+took + " ms");
System.out.println("result: " +d0);
return took;
}
@Test
public void testSquaring() {
int repetitions = 10;
long sum = 0;
for (int i = 0; i < repetitions; i++) {
sum += cut.squaring();
System.out.println("accumulated: "+ sum + "\n-------------------");
}
double avg = sum/repetitions;
System.out.println("average: "+avg);
}
And here are the results:
took: 244 ms
result: 0.0
accumulated: 244
-------------------
took: 302 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
took: 0 ms
result: 0.0
accumulated: 546
-------------------
average: 54.0