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

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

}
主站蜘蛛池模板: 梁河县| 营口市| 万载县| 红原县| 临潭县| 乐都县| 湟源县| 平阴县| 扎兰屯市| 交城县| 凤翔县| 江陵县| 柳河县| 恭城| 无为县| 贡山| 菏泽市| 贵阳市| 麻阳| 阳原县| 福清市| 沛县| 阿拉善右旗| 榆中县| 河间市| 天长市| 即墨市| 富锦市| 集贤县| 苍溪县| 龙川县| 益阳市| 全州县| 柳江县| 昌乐县| 铁岭市| 台南市| 福海县| 隆尧县| 天祝| 藁城市|