Skip to content

Instantly share code, notes, and snippets.

@PyvesB
Created September 11, 2018 17:48
Show Gist options
  • Save PyvesB/4d3a419168d1f6b459b4667db657b47e to your computer and use it in GitHub Desktop.
Save PyvesB/4d3a419168d1f6b459b4667db657b47e to your computer and use it in GitHub Desktop.
JMH example for string manipulations
package io.github.pyvesb.jmh;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RandomStringUtils;
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.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Fork(value = 2, jvmArgsAppend = "-Djmh.stack.lines=3")
@Warmup(iterations = 20)
@Measurement(iterations = 20)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ReplacementsBenchmark {
private static final Pattern PATTERN = Pattern.compile("\\s");
private String value;
@Setup
public void setup() {
value = RandomStringUtils.random(32, " abcdefghijklmnopqrstuvwxyz1234567890 ");
}
@Benchmark
public void replaceAll(Blackhole blackhole) {
blackhole.consume(value.replaceAll("\\s", "_"));
}
@Benchmark
public void replaceAll_precompiled_pattern(Blackhole blackhole) {
blackhole.consume(PATTERN.matcher(value).replaceAll("_"));
}
@Benchmark
public void replace_strings(Blackhole blackhole) {
blackhole.consume(value.replace(" ", "_"));
}
@Benchmark
public void replace_chars(Blackhole blackhole) {
blackhole.consume(value.replace(' ', '_'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment