Why is 2 * (i * i) faster than 2 * i * i in Java?
Hello everyone! I'm writing a simple benchmark to compare multiplication performance in Java. I noticed strange behavior: code with the expression `2 * (i * i)` runs consistently faster than `2 * i * i`. Here's an example:
```java
public class Test {
public static void main(String[] args) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++) {
sum += 2 * i * i; // slow
}
System.out.println(sum);
System.out.println("Time: " + (System.nanoTime() - start) / 1_000_000 + " ms");
}
}
```
If I replace `2 * i * i` with `2 * (i * i)`, the execution time decreases by almost half! I expected there would be no difference, since mathematically it's the same thing. Maybe it's related to the order of evaluation and
No answers yet.
Log in to leave an answer