Created
August 27, 2023 19:22
-
-
Save fabiolimace/d7901a2ad155980b1ae6ff25abea3700 to your computer and use it in GitHub Desktop.
Benchmark string inserting using concatenation vs StringBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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-"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BENCHMARK RESULT:
Conclusion: the method that uses string builder is almost 3x faster than the method using concatenation.