DecimalFormatが一番速い。
DecimalFormat, MessageFormat, String.format を比較。
だいたい予想通りの結果。
MessageFormatが一番遅いのか。
実行回数:1000
MessageFormat: time=83ms 35ms 15ms 13ms 13ms
String.format: time=44ms 27ms 13ms 10ms 10ms
DecimalFormat: time=14ms 9ms 8ms 9ms 9ms
実行回数:10000
MessageFormat: time=139ms 126ms 130ms 127ms 126ms
String.format: time=95ms 95ms 95ms 94ms 94ms
DecimalFormat: time=76ms 75ms 75ms 74ms 74ms
実行回数:100000
MessageFormat: time=1247ms 1204ms 1082ms 1078ms 1079ms
String.format: time=928ms 928ms 933ms 930ms 927ms
DecimalFormat: time=628ms 627ms 628ms 628ms 629ms
実行回数:500000
MessageFormat: time=5397ms 5389ms 5391ms 5388ms 5387ms
String.format: time=4627ms 4634ms 4634ms 4632ms 4630ms
DecimalFormat: time=3138ms 3140ms 3136ms 3137ms 3139ms
テストコード
interface Process { String title(); void run(); } public static void main(String[] args) throws IOException { final double data = Math.PI; final int tryCount = 5; final int[] loopCounts = new int[] { 1000, 10000, 100000, 500000 }; Process[] procs = new Process[] { new Process() { @Override public String title() { return "MessageFormat"; } @Override public void run() { MessageFormat.format("{0,number,#.#######}", data); } }, new Process() { @Override public String title() { return "String.format"; } @Override public void run() { String.format("%.7f", data); } }, new Process() { @Override public String title() { return "DecimalFormat"; } @Override public void run() { new DecimalFormat("0.0000000").format(data); } }, }; for (int lc : loopCounts) { System.out.println("実行回数:" + lc); for (Process process: procs) { System.out.print(process.title() + ": time="); for (int j= 0; j < tryCount; j++) { long t = System.currentTimeMillis(); for (int i = 0; i < lc; i++) { process.run(); } System.out.print((System.currentTimeMillis() - t) + "ms "); } System.out.println(); } } }