Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fabiolimace/d7901a2ad155980b1ae6ff25abea3700 to your computer and use it in GitHub Desktop.
Save fabiolimace/d7901a2ad155980b1ae6ff25abea3700 to your computer and use it in GitHub Desktop.
Benchmark string inserting using concatenation vs StringBuilder
package benchmark;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
@Fork(1)
@Threads(1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 3)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class BenchmarkInsertUsingConcatVsStringBuilder {
public static String insertUsingConcatenation(String str, String insert) {
final int position = 10;
return str.substring(0, position) + insert + str.substring(position);
}
public static String insertUsingStringBuilder(String str, String insert) {
final int position = 10;
StringBuilder builder = new StringBuilder(str);
builder.insert(position, insert);
return builder.toString();
}
private static final String string = "00000000000000000000000000"; // ZERO ULID
@Benchmark
public String insert_using_concatenation() {
return insertUsingConcatenation(string, "-AAAAAAA-");
}
@Benchmark
public String insert_using_string_builder() {
return insertUsingStringBuilder(string, "-AAAAAAA-");
}
}
@fabiolimace
Copy link
Author

fabiolimace commented Aug 27, 2023

BENCHMARK RESULT:

    Benchmark                                Mode  Cnt      Score      Error   Units
    Throughput.insert_using_concatenation   thrpt    5  13206,744 ± 1158,203  ops/ms
    Throughput.insert_using_string_builder  thrpt    5  38780,207 ± 2134,693  ops/ms (2.9x)

Conclusion: the method that uses string builder is almost 3x faster than the method using concatenation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment