|
| 1 | +package de.rieckpil.blog.jmh; |
| 2 | + |
| 3 | +import java.util.concurrent.TimeUnit; |
| 4 | + |
| 5 | +import org.openjdk.jmh.annotations.Benchmark; |
| 6 | +import org.openjdk.jmh.annotations.BenchmarkMode; |
| 7 | +import org.openjdk.jmh.annotations.Mode; |
| 8 | +import org.openjdk.jmh.annotations.OutputTimeUnit; |
| 9 | +import org.openjdk.jmh.annotations.Param; |
| 10 | +import org.openjdk.jmh.annotations.Scope; |
| 11 | +import org.openjdk.jmh.annotations.State; |
| 12 | +import org.openjdk.jmh.runner.Runner; |
| 13 | +import org.openjdk.jmh.runner.options.Options; |
| 14 | +import org.openjdk.jmh.runner.options.OptionsBuilder; |
| 15 | + |
| 16 | +@State(Scope.Thread) |
| 17 | +@BenchmarkMode(Mode.AverageTime) |
| 18 | +@OutputTimeUnit(TimeUnit.NANOSECONDS) |
| 19 | +public class StringConcatenationBenchmark { |
| 20 | + |
| 21 | + @Param({"5", "10", "15"}) |
| 22 | + private int iterations; |
| 23 | + |
| 24 | + public static void main(String[] args) throws Exception { |
| 25 | + Options opt = new OptionsBuilder() |
| 26 | + .include(StringConcatenationBenchmark.class.getSimpleName()) |
| 27 | + .forks(1) |
| 28 | + .warmupIterations(3) |
| 29 | + .measurementIterations(5) |
| 30 | + .build(); |
| 31 | + |
| 32 | + new Runner(opt).run(); |
| 33 | + } |
| 34 | + |
| 35 | + @Benchmark |
| 36 | + public String testStringBuilder() { |
| 37 | + StringBuilder sb = new StringBuilder(); |
| 38 | + for (int i = 0; i < iterations; i++) { |
| 39 | + sb.append("test"); |
| 40 | + } |
| 41 | + return sb.toString(); |
| 42 | + } |
| 43 | + |
| 44 | + @Benchmark |
| 45 | + public String testStringConcatenation() { |
| 46 | + String result = ""; |
| 47 | + for (int i = 0; i < iterations; i++) { |
| 48 | + result += "test"; |
| 49 | + } |
| 50 | + return result; |
| 51 | + } |
| 52 | +} |
0 commit comments