gnaggnoyil
gnaggnoyil

PrintWriter.print()和PrintWriter.printf()效率對比

測試平臺:

硬件:IBM ThinkPad X60,Intel T2400 CPU+1G DDR2

軟件:JDK1.6

測試用程序:

測試PrintWriter.print()用程序:

import java.io.*;
import java.text.*;
public class PrintTest{
public static void main(String args[])throws IOException{
PrintWriter output=new PrintWriter(new FileWriter("out.txt"));
long time1=System.currentTimeMillis();
DecimalFormat fmt=new DecimalFormat("0.######");
for(int i=0;i<10000000;i++)
output.println(fmt.format(i));
long time2=System.currentTimeMillis();
output.close();
output=new PrintWriter(System.out);
output.println(Long.toString(time2-time1)+" ms.");
output.close();
}
}

測試PrintWriter.printf()用程序:

import java.io.*;
public class PrintfTest{
public static void main(String args[])throws IOException{
PrintWriter output=new PrintWriter(new FileWriter("out.txt"));
long time1=System.currentTimeMillis();
double d=4.6;
for(int i=0;i<10000000;i++)
output.printf("%.6f\n",d);
long time2=System.currentTimeMillis();
output.close();
output=new PrintWriter(System.out);
output.println(Long.toString(time2-time1)+" ms.");
output.close();
}
}

測試結果:PrintWriter.print()和PrintWriter.printf()效率對比PrintWriter.print()和PrintWriter.printf()效率對比給咱的破本子給跪了Orz...循環才一千萬就一個個跑這麼長時間Orz...
另外在一開始的時候printf()曾經拋出過這樣一個異常來:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'l'
at java.util.Formatter$FormatSpecifier.conversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintWriter.format(Unknown Source)
at java.io.PrintWriter.printf(Unknown Source)
at PrintfTest.main(PrintfTest.java:8)PrintWriter.print()和PrintWriter.printf()效率對比由於JDK1.5的時候SUM還沒有被甲骨文收購,所以我只想說:"DOG SUN的SUN我SUN[你妹的敏感词]"PrintWriter.print()和PrintWriter.printf()效率對比直接用Formatter來實現print(),這不是逼人用print()么……