Skip to content

Commit

Permalink
add JMH sample
Browse files Browse the repository at this point in the history
  • Loading branch information
rieckpil committed Feb 11, 2025
1 parent 59629bf commit 0ae1f58
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
14 changes: 14 additions & 0 deletions spring-boot-example/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,20 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package de.rieckpil.blog.jmh;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class StringConcatenationBenchmark {

@Param({"5", "10", "15"})
private int iterations;

public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(StringConcatenationBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(3)
.measurementIterations(5)
.build();

new Runner(opt).run();
}

@Benchmark
public String testStringBuilder() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++) {
sb.append("test");
}
return sb.toString();
}

@Benchmark
public String testStringConcatenation() {
String result = "";
for (int i = 0; i < iterations; i++) {
result += "test";
}
return result;
}
}

0 comments on commit 0ae1f58

Please sign in to comment.