Skip to content

Instantly share code, notes, and snippets.

@punya
Last active December 20, 2015 18:59
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 punya/6179953 to your computer and use it in GitHub Desktop.
Save punya/6179953 to your computer and use it in GitHub Desktop.
Benchmarking SLF4J placeholders vs plain old concatenation.
import org.slf4j.helpers.MessageFormatter;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.caliper.runner.CaliperMain;
public final class PlaceholdersBenchmark extends Benchmark {
public static void main(String[] args) {
CaliperMain.main(PlaceholdersBenchmark.class, args);
}
private enum MessageCreator {
CONCATENATION {
@Override
String create(int x) {
return "hello " + x;
}
@Override
String create(int x, int y) {
return "hello " + x + " goodbye " + y;
}
@Override
String create(int x, int y, int z) {
return "hello " + x + " goodbye " + y + " wingus " + z;
}
},
PLACEHOLDER {
@Override
String create(int x) {
return MessageFormatter.format("hello {}", x).toString();
}
@Override
String create(int x, int y) {
return MessageFormatter.format("hello {} goodbye {}", x, y)
.toString();
}
@Override
String create(int x, int y, int z) {
return MessageFormatter.arrayFormat(
"hello {} goodbye {} wingus {}",
new Object[] { x, y, z }).toString();
}
},
STRING_FORMAT {
@Override
String create(int x) {
return String.format("hello %d", x);
}
@Override
String create(int x, int y) {
return String.format("hello %d goodbye %d", x, y);
}
@Override
String create(int x, int y, int z) {
return String.format("hello %d goodbye %d wingus %d", x, y, z);
}
},
STRINGFORMATTER_FORMAT {
@Override
String create(int x) {
return StringFormatter.format("hello %d", x);
}
@Override
String create(int x, int y) {
return StringFormatter.format("hello %d goodbye %d", x, y);
}
@Override
String create(int x, int y, int z) {
return StringFormatter.format("hello %d goodbye %d wingus %d", x, y, z);
}
};
abstract String create(int x);
abstract String create(int x, int y);
abstract String create(int x, int y, int z);
}
@Param
private MessageCreator creator;
public int timeOneParameter(int count) {
int result = 0;
for (int i = 0; i < count; ++i) {
result ^= creator.create(i).codePointAt(0);
}
return result;
}
public int timeTwoParameter(int count) {
int result = 0;
for (int i = 0; i < count; ++i) {
result ^= creator.create(i, i + 1).codePointAt(0);
}
return result;
}
public int timeThreeParameter(int count) {
int result = 0;
for (int i = 0; i < count; ++i) {
result ^= creator.create(i, i + 1, i + 2).codePointAt(0);
}
return result;
}
}
@punya
Copy link
Author

punya commented Aug 7, 2013

Benchmark results: http://goo.gl/4fZEjl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment