Here is a JMH benchmark:
@OutputTimeUnit(TimeUnit.SECONDS)
@BenchmarkMode({ Mode.Throughput })
@Warmup(iterations = 10)
@Fork(value = 1)
@State(Scope.Benchmark)
public class MyBenchmark {
private static final double CONSTANT = 1.6712 * 1000 * 60;
private double x = 0;
@Benchmark
public void testCaseOne() {
for (double i = 1; i < 1000_000; i++) {
x += i * 1.6712 * 1000 * 60;
}
}
@Benchmark
public void testCaseTwo() {
for (double i = 1; i < 1000_000; i++) {
x += i * (1.6712 * 1000 * 60);
}
}
@Benchmark
public void testCaseThree() {
for (double i = 1; i < 1000_000; i++) {
x += i * 100272;
}
}
@Benchmark
public void testCaseFour() {
final double constant = 1.6712 * 1000 * 60;
for (double i = 1; i < 1000_000; i++) {
x += i * constant;
}
}
@Benchmark
public void testCaseFive() {
for (double i = 1; i < 1000_000; i++) {
x += i * CONSTANT;
}
}
}
And the results:
Benchmark Mode Cnt Score Error Units
MyBenchmark.testCaseOne thrpt 20 680,452 ± 15,700 ops/s
MyBenchmark.testCaseTwo thrpt 20 721,542 ± 14,131 ops/s
MyBenchmark.testCaseThree thrpt 20 729,411 ± 17,031 ops/s
MyBenchmark.testCaseFour thrpt 20 735,255 ± 16,001 ops/s
MyBenchmark.testCaseFive thrpt 20 719,481 ± 5,338 ops/s
Java version:
openjdk version "1.8.0_45-internal"
OpenJDK Runtime Environment (build 1.8.0_45-internal-b14)
OpenJDK 64-Bit Server VM (build 25.45-b02, mixed mode)
As you can see there is no significant difference in the throughput, so you can write it in the way it is most clear and easier to understand.
Regarding my previous benchmark results:
Benchmark Mode Cnt Score Error Units
MyBenchmark.testCaseOne thrpt 20 228,285 ± 2,232 ops/s
MyBenchmark.testCaseTwo thrpt 20 593,755 ± 8,165 ops/s
MyBenchmark.testCaseThree thrpt 20 1035,549 ± 20,908 ops/s
The previous benchmark was broken - the counter in the for loop was of type int
and in testCaseThree
it was doing integer multiplication and that's the reason it was so much faster. The other results were also affected by this bug in the benchmark.
It's still interesting though why the mixed integer-double multiplication is so much slower than both pure int-int and double-double multiplication. Maybe because of type casting?