|
| 1 | +package com.baeldung.performance; |
| 2 | + |
| 3 | +import org.openjdk.jmh.annotations.*; |
| 4 | +import org.openjdk.jmh.runner.Runner; |
| 5 | +import org.openjdk.jmh.runner.options.Options; |
| 6 | +import org.openjdk.jmh.runner.options.OptionsBuilder; |
| 7 | + |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.Arrays; |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.List; |
| 12 | +import java.util.concurrent.TimeUnit; |
| 13 | + |
| 14 | +@BenchmarkMode(Mode.AverageTime) |
| 15 | +@OutputTimeUnit(TimeUnit.NANOSECONDS) |
| 16 | +@Measurement(batchSize = 100000, iterations = 10) |
| 17 | +@Warmup(batchSize = 100000, iterations = 10) |
| 18 | +public class ArraySortBenchmark { |
| 19 | + |
| 20 | + @State(Scope.Thread) |
| 21 | + public static class Initialize { |
| 22 | + |
| 23 | + String[] array = new String[]{"A", "AB", "B"}; |
| 24 | + |
| 25 | + List<String> list = new ArrayList<>(); |
| 26 | + |
| 27 | + @Setup(Level.Trial) |
| 28 | + public void setUp() { |
| 29 | + list.add("A"); |
| 30 | + list.add("AB"); |
| 31 | + list.add("B"); |
| 32 | + } |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + @Benchmark |
| 37 | + public String[] benchmarkArraysSort(ArraySortBenchmark.Initialize state) { |
| 38 | + Arrays.sort(state.array); |
| 39 | + return state.array; |
| 40 | + } |
| 41 | + |
| 42 | + @Benchmark |
| 43 | + public List<String> benchmarkCollectionsSort(ArraySortBenchmark.Initialize state) { |
| 44 | + Collections.sort(state.list); |
| 45 | + return state.list; |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String[] args) throws Exception { |
| 49 | + Options options = new OptionsBuilder() |
| 50 | + .include(ArraySortBenchmark.class.getSimpleName()).threads(1) |
| 51 | + .forks(1).shouldFailOnError(true) |
| 52 | + .shouldDoGC(true) |
| 53 | + .jvmArgs("-server").build(); |
| 54 | + new Runner(options).run(); |
| 55 | + } |
| 56 | +} |
0 commit comments