官术网_书友最值得收藏!

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;
}

}
主站蜘蛛池模板: 和平区| 万安县| 宣恩县| 留坝县| 波密县| 罗定市| 邻水| 武穴市| 宁阳县| 鸡泽县| 伊宁市| 句容市| 泸定县| 宜兰市| 易门县| 礼泉县| 临漳县| 柘荣县| 新巴尔虎左旗| 平阴县| 徐水县| 自贡市| 东乌珠穆沁旗| 乌拉特后旗| 容城县| 富平县| 石楼县| 永寿县| 永修县| 兴隆县| 呼图壁县| 达拉特旗| 普兰县| 灵石县| 中宁县| 沐川县| 定州市| 英山县| 同心县| 永定县| 镶黄旗|