Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Why Is 2 * (i * i) Faster Than 2 * i * i in Java?

$
0
0

1. Overview

When optimizing code, even small differences in expression syntax can impact performance. One such example is the difference between 2 * (i * i) and 2 * i * i in Java. At first glance, these two expressions might seem identical, but subtle differences in how they’re evaluated can lead to performance discrepancies.

In this tutorial, we’ll explore why 2 * (i * i) is generally faster than 2 * i * i and dive into the underlying reasons. Let’s begin.

2. Understanding the Expression

Let’s break down the two expressions. In this expression, the multiplication of i * i happens first, followed by multiplying the result by 2:

2 * (i * i)

In this expression, the evaluation proceeds from left to right:

2 * i * i

First, 2 * i is calculated, and then the result is multiplied by i.

3. Performance Comparison

Even though both expressions theoretically yield the same result, the order of operations can influence performance.

3.1. Compiler Optimization

Java compilers like the Just-In-Time (JIT) compiler in the JVM are sophisticated and can optimize code at runtime. However, compilers rely heavily on the clarity of the code to make optimizations:

  • 2 * (i * i): The parentheses clearly define the order of operations, making it easier for the compiler to optimize the multiplication.
  • 2 * i * i: The less explicit order of operations may result in less efficient optimization. The compiler might not optimize the code as efficiently as with 2 * (i * i).

In essence, 2 * (i * i) provides the compiler with a clear indication of how to perform the calculations, which can lead to a better-optimized bytecode.

3.2. Integer Overflow Considerations

Integer overflow occurs when a calculation produces a value larger than the maximum value that an int can store (2^31 – 1 for a 32-bit integer). While neither expression inherently causes overflow more than the other, the way the calculations are structured can affect how overflow is handled:

  • 2 * i * i: If i is large, the intermediate result of 2 * i might approach the overflow threshold. This could lead to potential issues during the final multiplication by i.
  • 2 * (i * i): In this expression, we better understand whether the multiplication by 2 will cause overflow after squaring i. Therefore, this makes the expression slightly safer in scenarios involving large values.

3.3. CPU-Level Execution

At the CPU level, instructions are executed in specific orders that vary based on how the operations are grouped:

  • 2 * (i * i): The CPU might optimize this operation better. Since the squaring (i * i) is more straightforward.
  • 2 * i * i: The CPU might require additional cycles to handle the intermediate result of 2 * i, especially if this result is large.

In most real-world scenarios, the performance difference between 2 * (i * i) and 2 * i * i is likely minimal for smaller i values. However, the difference can become significant when i is large or when this operation is performed repeatedly in a performance-critical code section.

4. Performance Testing Using JMH

Now, to prove the theory, let’s play with actual data. To be more precise, we’ll present the JMH (Java Microbenchmark Harness) test results of the most common collection operations.

First, we’ll present the main parameters of our benchmark tests:

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
public class MultiplicationBenchmark {
}

Then we’ll set the warm-up iterations number to 3.

Now, it’s time to add the benchmark tests for the following small and large values:

private int smallValue = 255;
private int largeValue = 2187657;
@Benchmark
public int testSmallValueWithParentheses() {
    return 2 * (smallValue * smallValue);
}
@Benchmark
public int testSmallValueWithoutParentheses() {
    return 2 * smallValue * smallValue;
}
@Benchmark
public int testLargeValueWithParentheses() {
    return 2 * (largeValue * largeValue);
}
@Benchmark
public int testLargeValueWithoutParentheses() {
    return 2 * largeValue * largeValue;
}

Here are the test results for our calculations with and without parentheses:

Benchmark                                             Mode  Cnt  Score   Error  Units
MultiplicationBenchmark.largeValueWithParentheses     avgt    5  1.066 ± 0.168  ns/op
MultiplicationBenchmark.largeValueWithoutParentheses  avgt    5  1.283 ± 0.392  ns/op
MultiplicationBenchmark.smallValueWithParentheses     avgt    5  1.173 ± 0.218  ns/op
MultiplicationBenchmark.smallValueWithoutParentheses  avgt    5  1.222 ± 0.287  ns/op

The results show the average time (in nanoseconds per operation, ns/op) taken for different multiplication scenarios based on the presence or absence of parentheses.

Here’s a breakdown:

MultiplicationBenchmark.largeValueWithParentheses (1.066 ± 0.168 ns/op):

  • This represents multiplying large values with parentheses.
  • The average time taken is 1.066 nanoseconds, with a margin of error of ±0.168.

MultiplicationBenchmark.largeValueWithoutParentheses (1.283 ± 0.392 ns/op):

  • This represents multiplying large values without parentheses.
  • The average time is 1.283 nanoseconds, with a margin of error of ±0.392.

MultiplicationBenchmark.smallValueWithParentheses (1.173 ± 0.218 ns/op):

  • This represents multiplying small values with parentheses.
  • The average time is 1.173 nanoseconds, with a margin of error of ±0.218.

MultiplicationBenchmark.smallValueWithoutParentheses (1.222 ± 0.287 ns/op):

  • This represents multiplying small values without parentheses.
  • The average time is 1.222 nanoseconds, with a margin of error of ±0.287.

Faster Approach: The multiplication involving large values with parentheses is the fastest (1.066 ns/op).
Slower Approach: Large values without parentheses take the most time (1.283 ns/op).

5. Conclusion

In this article, we saw that while both 2 * (i * i) and 2 * i * i yield the same result, 2 * (i * i) is often faster. Parentheses offer a slight speed advantage in large and small value multiplications, though the difference is minor and within the margin of error for smaller values.

This suggests that parentheses might result in slightly more optimized multiplication, but the performance difference is marginal. It provides more predictable intermediate results, better compiler optimization opportunities, reduced risk of overflow, and more efficient CPU execution. When writing performance-critical code, we should consider not just correctness but also how the code will execute. Small changes, like the placement of parentheses, can significantly impact performance, showing the importance of understanding the mechanics of both the language and the hardware.

As always, the source code of all these examples is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>