Skip to content

Instantly share code, notes, and snippets.

@edwardbeckett
Last active January 4, 2016 03:38
Show Gist options
  • Save edwardbeckett/e00d84471311b87215c2 to your computer and use it in GitHub Desktop.
Save edwardbeckett/e00d84471311b87215c2 to your computer and use it in GitHub Desktop.
StringPerformance BenchMark :: building strings within loops :: 10K increment to 100K
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/**
* @implNote :: run with java -jar benchmarks.jar StringPerf -wi 10 -i 10 -f 4
* @author Edward Beckett <[email protected]>
* @since 12/24/2015
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class StringPerf {
private int[] data;
@Param({"10000", "20000", "30000", "40000", "50000", "60000", "70000", "80000", "90000", "100000"})
private int reps;
@Setup
public void init() {
reps = this.reps;
}
@Benchmark
public void assignmentBench(Blackhole bh) {
assignment(reps);
bh.consume(reps);
}
@Benchmark
public void builderBench(Blackhole bh) {
builder(reps);
bh.consume(reps);
}
@Benchmark
public void concatBench(Blackhole bh) {
concat(reps);
bh.consume(reps);
}
static void assignment(int rep) {
int x = 0;
String s = "String ";
while (x < rep) {
s += "String ";
++x;
}
}
static void builder(int rep) {
int x = 0;
StringBuilder builder = new StringBuilder("String ");
while (x < rep) {
builder.append("String ");
++x;
}
}
static void concat(int rep) {
int x = 0;
String s = "String ";
while (x < rep) {
s = s.concat("String ");
++x;
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(StringPerf.class.getSimpleName())
.warmupIterations(10)
.measurementIterations(10)
.forks(4)
.build();
new Runner(opt).run();
}
}
Test 10000 20000 30000 40000 50000 60000 70000 80000 90000 100000
StringBuilder 128709.765 255235.171 427853.591 524721.434 637707.136 767883.754 850727.563 954963.585 1037265.986 1114734.247
Concat 66624356.104 278265469.575 638778227.200 1146925954.300 1792719929.400 2572104397.800 3522111595.800 4605412904.500 5829298725.000 7182267722.300
Assignment 70502163.519 313045828.592 790608891.200 1604476535.500 2613965931.600 3784940006.700 5102860455.700 6707762997.200 9070591528.600 11086582529.700
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment