Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. package test;
  2.  
  3. import org.openjdk.jmh.annotations.Benchmark;
  4. import org.openjdk.jmh.annotations.BenchmarkMode;
  5. import org.openjdk.jmh.annotations.Mode;
  6. import org.openjdk.jmh.annotations.OutputTimeUnit;
  7. import org.openjdk.jmh.annotations.Scope;
  8. import org.openjdk.jmh.annotations.State;
  9. import org.openjdk.jmh.infra.Blackhole;
  10.  
  11. import java.util.Random;
  12. import java.util.concurrent.TimeUnit;
  13.  
  14. import static io.vavr.API.$;
  15. import static io.vavr.API.Case;
  16. import static io.vavr.API.Match;
  17. import static test.MyBenchmark.TestEnum.A;
  18. import static test.MyBenchmark.TestEnum.B;
  19. import static test.MyBenchmark.TestEnum.C;
  20. import static test.MyBenchmark.TestEnum.values;
  21.  
  22.  
  23. @BenchmarkMode(Mode.AverageTime)
  24. @OutputTimeUnit(TimeUnit.MICROSECONDS)
  25. public class MyBenchmark {
  26.  
  27.     public enum TestEnum {A, B, C}
  28.  
  29.     @State(Scope.Thread)
  30.     public static class MyState {
  31.         public Random r = new Random();
  32.     }
  33.  
  34.     @Benchmark
  35.     public void ifMethod(Blackhole bh, MyState state) {
  36.         TestEnum sample = TestEnum.values()[state.r.nextInt(values().length)];
  37.         TestEnum result;
  38.         if (sample == A) {
  39.             result = B;
  40.         } else if (sample == B) {
  41.             result = C;
  42.         } else if (sample == C) {
  43.             result = A;
  44.         } else {
  45.             result = A;
  46.         }
  47.         bh.consume(result);
  48.     }
  49.  
  50.     @Benchmark
  51.     public void switchMethod(Blackhole bh, MyState state) {
  52.         TestEnum sample = TestEnum.values()[state.r.nextInt(values().length)];
  53.         TestEnum result;
  54.         switch (sample) {
  55.             case A:
  56.                 result = B;
  57.             case B:
  58.                 result = C;
  59.             case C:
  60.                 result = A;
  61.             default:
  62.                 result = A;
  63.         }
  64.         bh.consume(result);
  65.     }
  66.  
  67.     @Benchmark
  68.     public void vavrMethod(Blackhole bh, MyState state) {
  69.         TestEnum sample = TestEnum.values()[state.r.nextInt(values().length)];
  70.         bh.consume(Match(sample).of(
  71.                 Case($(A), B),
  72.                 Case($(B), C),
  73.                 Case($(C), A),
  74.                 Case($(), A)
  75.         ));
  76.     }
  77.  
  78.     public static void main(String[] args) throws Exception {
  79.         org.openjdk.jmh.Main.main(args);
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement