Skip to content

Instantly share code, notes, and snippets.

@AdamStelmaszczyk
Created June 25, 2015 21:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AdamStelmaszczyk/72f0a2511428e36e495c to your computer and use it in GitHub Desktop.
Save AdamStelmaszczyk/72f0a2511428e36e495c to your computer and use it in GitHub Desktop.
Should I use Java's String.format() if performance is important?
package org.sample;
import org.openjdk.jmh.annotations.*;
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.concurrent.TimeUnit;
@OutputTimeUnit(TimeUnit.SECONDS)
@BenchmarkMode({Mode.Throughput})
@Warmup(iterations = 10)
@Fork(value = 1)
@State(Scope.Benchmark)
public class MyBenchmark {
private static final int LOOPS = 1000;
@Benchmark
public int testOld() {
int counter = 0;
for (int i = 0; i < LOOPS; i++) {
String s = "What do you get if you multiply " + counter + " by " + counter + "?";
counter += s.length();
}
return counter;
}
@Benchmark
public int testNew() {
int counter = 0;
for (int i = 0; i < LOOPS; i++) {
String s = String.format("What do you get if you multiply %d by %d?", counter, counter);
counter += s.length();
}
return counter;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(MyBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment