- Mastering High Performance with Kotlin
- Igor Kucherenko
- 212字
- 2021-06-25 20:55:26
Constant folding
Constant folding is the flip side of the DCE. If your calculation is based on constants and the result is often exactly the same, the JVM will detect this and replace the calculation with the result. To make sure this doesn't happen, we can move the computation outside the internal JMH loop. Constant folding can be prevented by always reading the inputs from non-final instance fields of a state object. In this case, the result will be based on fields of the state object:
@Benchmark
public int testMethod() {
int a = 3;
int b = 4;
return a + b;
}
So, in the preceding code, the JVM can detect that the result value is based on two constants, a and b, and can replace our code with this:
public class MyBenchmark { @Benchmark public int testMethod() { int c = 3; return c; } }
Or it can just return 3 or replace the invocation of this method with 3. To solve this problem, you should rewrite the code as follows:
public class MyBenchmark {
@State(Scope.Thread)
public static class MyState {
int a = 3;
int b = 4;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public int testMethod(MyState state) {
return state.a + state.b;
}
}
推薦閱讀
- Django+Vue.js商城項(xiàng)目實(shí)戰(zhàn)
- Android應(yīng)用程序開發(fā)與典型案例
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- Apache Spark Graph Processing
- C#程序設(shè)計(jì)教程
- Essential Angular
- Microsoft Dynamics GP 2013 Reporting, Second Edition
- Getting Started with SQL Server 2012 Cube Development
- 鋒利的SQL(第2版)
- FFmpeg入門詳解:音視頻原理及應(yīng)用
- Rust Essentials(Second Edition)
- Python編程實(shí)戰(zhàn)
- Android程序設(shè)計(jì)基礎(chǔ)
- Android系統(tǒng)原理及開發(fā)要點(diǎn)詳解