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

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

}
主站蜘蛛池模板: 三门县| 甘泉县| 砚山县| 军事| 惠安县| 阳东县| 萍乡市| 巴林右旗| 高碑店市| 丁青县| 郑州市| 呼和浩特市| 诸暨市| 彰化市| 武宣县| 安图县| 筠连县| 广昌县| 武威市| 哈尔滨市| 新沂市| 昌宁县| 滦南县| 宁都县| 湟源县| 锡林浩特市| 肃北| 芮城县| 建平县| 栾川县| 隆子县| 华阴市| 正宁县| 山阴县| 栾城县| 孟州市| 高阳县| 东明县| 驻马店市| 柳河县| 都匀市|