Skip to content

Instantly share code, notes, and snippets.

@danielshaya
Created February 17, 2015 17:39
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 danielshaya/b56495bd62f89c379327 to your computer and use it in GitHub Desktop.
Save danielshaya/b56495bd62f89c379327 to your computer and use it in GitHub Desktop.
Benchmark to concatenate 2 Strings
package org.sample;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Thread)
public class TwoStringsBenchmark {
private String[] strings;
@Setup
public void setupTest(){
strings = new String[2];
strings[0] = UUID.randomUUID().toString().substring(0,10);
strings[1] = UUID.randomUUID().toString().substring(0,10);
}
@Benchmark
public void testPlus(Blackhole bh) {
bh.consume(strings[0] + strings[1]);
}
@Benchmark
public void testStringBuilder(Blackhole bh) {
StringBuilder sb = new StringBuilder();
sb.append(strings[0]).append(strings[1]);
bh.consume(sb.toString());
}
@Benchmark
public void testStringBuffer(Blackhole bh) {
StringBuffer sb = new StringBuffer();
sb.append(strings[0]).append(strings[1]);
bh.consume(sb.toString());
}
@Benchmark
public void testStringJoiner(Blackhole bh) {
bh.consume(String.join("", strings[0], strings[1]));
}
@Benchmark
public void testStringConcat(Blackhole bh) {
bh.consume(strings[0].concat(strings[1]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment