Created
February 17, 2015 17:39
-
-
Save danielshaya/b56495bd62f89c379327 to your computer and use it in GitHub Desktop.
Benchmark to concatenate 2 Strings
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 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