|
| 1 | +package com.howtodoinjava.core.string; |
| 2 | + |
| 3 | +import java.time.LocalTime; |
| 4 | +import java.util.concurrent.TimeUnit; |
| 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.Setup; |
| 12 | +import org.openjdk.jmh.annotations.State; |
| 13 | +import org.openjdk.jmh.runner.Runner; |
| 14 | +import org.openjdk.jmh.runner.options.Options; |
| 15 | +import org.openjdk.jmh.runner.options.OptionsBuilder; |
| 16 | + |
| 17 | +@State(Scope.Thread) |
| 18 | +public class StringConcatenationBenchmark { |
| 19 | + |
| 20 | + @Param({"10", "100", "1000"}) |
| 21 | + private int count; |
| 22 | + |
| 23 | + private String baseString; |
| 24 | + |
| 25 | + @Setup |
| 26 | + public void setup() { |
| 27 | + baseString = "SampleString"; |
| 28 | + } |
| 29 | + |
| 30 | + @Benchmark |
| 31 | + @BenchmarkMode(Mode.AverageTime) |
| 32 | + @OutputTimeUnit(TimeUnit.MICROSECONDS) |
| 33 | + public String testStringConcatenation() { |
| 34 | + String result = ""; |
| 35 | + for (int i = 0; i < count; i++) { |
| 36 | + result += baseString; |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | + @Benchmark |
| 42 | + @BenchmarkMode(Mode.AverageTime) |
| 43 | + @OutputTimeUnit(TimeUnit.MICROSECONDS) |
| 44 | + public String testStringBuilder() { |
| 45 | + StringBuilder builder = new StringBuilder(); |
| 46 | + for (int i = 0; i < count; i++) { |
| 47 | + builder.append(baseString); |
| 48 | + } |
| 49 | + return builder.toString(); |
| 50 | + } |
| 51 | + |
| 52 | + @Benchmark |
| 53 | + @BenchmarkMode(Mode.AverageTime) |
| 54 | + @OutputTimeUnit(TimeUnit.MICROSECONDS) |
| 55 | + public String testStringBuffer() { |
| 56 | + StringBuffer buffer = new StringBuffer(); |
| 57 | + for (int i = 0; i < count; i++) { |
| 58 | + buffer.append(baseString); |
| 59 | + } |
| 60 | + return buffer.toString(); |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) throws Exception { |
| 64 | + |
| 65 | + var name = "Alex"; |
| 66 | + var time = LocalTime.now(); |
| 67 | + |
| 68 | + String greeting = "Hello " + name + ", how are you?\nThe current time is " + time + " now!"; |
| 69 | + System.out.println(greeting); |
| 70 | + |
| 71 | + String greetingTemplate = STR."Hello \{name}, how are you?\nThe current time is \{time} now!"; |
| 72 | + System.out.println(greetingTemplate); |
| 73 | + |
| 74 | + Options opt = new OptionsBuilder() |
| 75 | + .include(StringConcatenationBenchmark.class.getSimpleName()) |
| 76 | + .forks(1) |
| 77 | + .build(); |
| 78 | + |
| 79 | + new Runner(opt).run(); |
| 80 | + } |
| 81 | +} |
| 82 | + |
0 commit comments