JMH: Using the same static object in all Benchmark tests

后端 未结 2 483
感情败类
感情败类 2021-01-04 17:10

I have a class that constructs some complicated data (imagine a large XML or JSON structure - that sort of thing). Constructing it takes time. So I want to construct it once

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 18:02

    I would just move all of your benchmark methods into one class, define your state object as an inner class, and inject the state to each of them:

    public class ParserBenchmarks {
    
      @State(Scope.Thread)
      public static class StateHolder {
        Parser parser = null;
    
        @Setup(Level.Iteration)
        public void setup()
        {
          parser = new Parser(TestSet.PARSE_ME);
        }
    
        public Parser getParser() {
          return parser;
        }
      }
    
      @Benchmark
      public int getId_123(StateHolder stateHolder) {
        return stateHolder.getParser().getId(123);
      }
    
      @Benchmark
      public int getId_456(StateHolder stateHolder) {
        return stateHolder.getParser().getId(456);
      }
    
    }
    

    Note that all of your benchmark methods should return values otherwise the compiler could eliminate it as dead code.

提交回复
热议问题