Performance
StringConcatBenchmark
- Path
- pkg19performance/jmh-demo/src/main/java/pkg19performance/jmh/StringConcatBenchmark.java
- Package
- pkg19performance
- Study order
- 0
- Run
- Read this file. It has no standalone main method.
- Dependencies
- org.openjdk.jmh.infra.Blackhole
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg19performance.jmh;2 3import org.openjdk.jmh.annotations.*;4import org.openjdk.jmh.infra.Blackhole;5 6import java.util.concurrent.TimeUnit;7 8/*9 * Run: mvn -q package -f pkg19performance/jmh-demo/pom.xml10 * java -jar pkg19performance/jmh-demo/target/benchmarks.jar -wi 1 -i 3 -f 111 */12@BenchmarkMode(Mode.AverageTime)13@OutputTimeUnit(TimeUnit.NANOSECONDS)14@State(Scope.Thread)15@Warmup(iterations = 1)16@Measurement(iterations = 3)17@Fork(1)18public class StringConcatBenchmark {19 20 @Benchmark21 public void stringConcat(Blackhole bh) {22 String s = "";23 for (int i = 0; i < 10; i++) s += i;24 bh.consume(s);25 }26 27 @Benchmark28 public void stringBuilder(Blackhole bh) {29 StringBuilder sb = new StringBuilder();30 for (int i = 0; i < 10; i++) sb.append(i);31 bh.consume(sb.toString());32 }33}