Skip to content

Instantly share code, notes, and snippets.

@wallrat
Created July 13, 2015 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallrat/1d4b1ab058ba68875ad1 to your computer and use it in GitHub Desktop.
Save wallrat/1d4b1ab058ba68875ad1 to your computer and use it in GitHub Desktop.
package scratch;
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;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Thread)
public class LoopStringsBenchmark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(LoopStringsBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
private String[] strings;
@Setup
public void setupTest() {
strings = new String[100];
for (int i = 0; i < 100; i++) {
strings[i] = UUID.randomUUID().toString().substring(0, 10);
}
}
@Benchmark
public void testPlus(Blackhole bh) {
String combined = "";
for (String s : strings) {
combined = combined + s;
}
bh.consume(combined);
}
@Benchmark
public void testStringBuilder(Blackhole bh) {
StringBuilder sb = new StringBuilder();
for (String s : strings) {
sb.append(s);
}
bh.consume(sb.toString());
}
@Benchmark
public void testStringBuffer(Blackhole bh) {
StringBuffer sb = new StringBuffer();
for (String s : strings) {
sb.append(s);
}
bh.consume(sb.toString());
}
@Benchmark
public void testStringJoiner(Blackhole bh) {
bh.consume(String.join("", strings));
}
@Benchmark
public void testStringConcat(Blackhole bh) {
String combined = "";
for (String s : strings) {
combined.concat(s);
}
bh.consume(combined);
}
}
// Java 8 results
//# Run complete. Total time: 00:00:51
//
// Benchmark Mode Cnt Score Error Units
// LoopStringsBenchmark.testPlus thrpt 10 80120.589 ± 18155.538 ops/s
// LoopStringsBenchmark.testStringBuffer thrpt 10 595825.572 ± 233297.303 ops/s
// LoopStringsBenchmark.testStringBuilder thrpt 10 596329.000 ± 270195.655 ops/s
// LoopStringsBenchmark.testStringConcat thrpt 10 428817.984 ± 96583.918 ops/s
// LoopStringsBenchmark.testStringJoiner thrpt 10 449707.702 ± 79852.503 ops/s
//
//
// Java 7 results
// Benchmark Mode Cnt Score Error Units
// LoopStringsBenchmark.testPlus thrpt 10 82123.780 ± 5162.099 ops/s
// LoopStringsBenchmark.testStringBuffer thrpt 10 526157.298 ± 67294.995 ops/s
// LoopStringsBenchmark.testStringBuilder thrpt 10 579148.486 ± 77417.358 ops/s
// LoopStringsBenchmark.testStringConcat thrpt 10 479200.469 ± 57042.272 ops/s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment