From c06e1ab413977ca03b370e04b70371f0871a5998 Mon Sep 17 00:00:00 2001 From: Kilian Schneider <48420258+Basler182@users.noreply.github.com> Date: Wed, 10 May 2023 16:39:34 +0200 Subject: [PATCH] BAEL-6185 reuse string builder performance (#13791) --- .../ReuseStringBuilderPerformance.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java new file mode 100644 index 0000000000..b403f859bc --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java @@ -0,0 +1,55 @@ +package com.baeldung.stringbuilder; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 100000, iterations = 10) +@Warmup(batchSize = 100000, iterations = 10) +@State(Scope.Thread) +public class ReuseStringBuilderPerformance { + + @Benchmark + public void benchmarkStringBuilder() { + for (int i = 0; i < 100; i++) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("baeldung"); + stringBuilder.toString(); + } + } + + @Benchmark + public void benchmarkStringBuilderReuseWithSetLength() { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < 100; i++) { + stringBuilder.append("baeldung"); + stringBuilder.toString(); + stringBuilder.setLength(0); + } + } + + @Benchmark() + public void benchmarkStringBuilderReuseWithDelete() { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < 100; i++) { + stringBuilder.append("baeldung"); + stringBuilder.toString(); + stringBuilder.delete(0, stringBuilder.length()); + } + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ReuseStringBuilderPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + +}