Skip to content

Instantly share code, notes, and snippets.

@moznion
Created January 21, 2015 06:11
Show Gist options
  • Save moznion/2e31a9d830c3a138984e to your computer and use it in GitHub Desktop.
Save moznion/2e31a9d830c3a138984e to your computer and use it in GitHub Desktop.
import java.util.Formatter;
public class Bench {
private String fileName = "foo.java";
private String className = "class.dayo";
private String methodName = "methodDayo";
private int lineNumber = 42;
public void benchStringBuilder() {
for (int i=0; i<1_000_000; ++i) {
new StringBuilder()
.append("File Name: ")
.append(fileName)
.append(", Class Name: ")
.append(className)
.append(", Method Name: ")
.append(methodName)
.append(", Line Number: ")
.append(lineNumber)
.toString();
}
}
public void benchStringFormat() {
for (int i=0; i<1_000_000; ++i) {
String.format("File name: %s, Class Name: %s, Method Name: %s, Line Number: %d", fileName, className, methodName, lineNumber);
}
}
public void benchFormatterFormat() {
for (int i=0; i<1_000_000; ++i) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("File name: %s, Class Name: %s, Method Name: %s, Line Number: %d", fileName, className, methodName, lineNumber);
}
}
}
/*
Score:
benchStringBuilder: 1 wallclock secs ( 0.99 usr + 0.05 sys = 1.03 CPU) @ 16.45/s (n=17)
benchStringFormat: 1 wallclock secs ( 1.89 usr + 0.00 sys = 1.90 CPU) @ 0.53/s (n=1)
benchFormatterFormat: 1 wallclock secs ( 1.83 usr + 0.00 sys = 1.84 CPU) @ 0.55/s (n=1)
Comparison chart:
Rate benchStringBuilder benchStringFormat benchFormatterFormat
benchStringBuilder 16.4/s -- 3009% 2916%
benchStringFormat 0.529/s -97% -- -3%
benchFormatterFormat 0.545/s -97% 3% --
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment