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

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

}
主站蜘蛛池模板: 湖州市| 阳泉市| 房产| 调兵山市| 峡江县| 郎溪县| 多伦县| 伽师县| 连云港市| 时尚| 麻栗坡县| 武隆县| 博兴县| 肇东市| 科尔| 林口县| 桂平市| 盘锦市| 鹤峰县| 门源| 枞阳县| 永昌县| 湘阴县| 德格县| 大丰市| 洪泽县| 金门县| 弋阳县| 永城市| 昌宁县| 安康市| 陕西省| 藁城市| 闽侯县| 寻乌县| 洪泽县| 翼城县| 杭州市| 竹溪县| 台山市| 娄底市|