格式化的代价

实际上向文件写数据只是输出代价的一部分。另一个可观的代价是数据格式化。考虑一个三部分程序,它像下面这样输出一行:

 The square of 5 is 25

方法 1

第一种方法简单的输出一个固定的字符串,了解固有的I/O开销:

 public class format1 {

   public static void main(String args[]) {

        final int COUNT = 25000;

      for (int i = 1; i <= COUNT; i++) {

            String s = "The square of 5 is 25\n";

            System.out.print(s);

        }

   }

}

方法2

第二种方法使用简单格式"+":

public class format2 {

   public static void main(String args[]) {

        int n = 5;

        final int COUNT = 25000;

        for (int i = 1; i <= COUNT; i++) {

            String s = "The square of " + n + " is " + n * n + "\n";

            System.out.print(s);

        }

   }

}

方法 3

第三种方法使用java.text包中的 MessageFormat 类:

import java.text.*;

 

public class format3 {

   public static void main(String args[]) {

        MessageFormat fmt = new MessageFormat("The square of {0} is {1}\n");

        Object values[] = new Object[2];

        int n = 5;

        values[0] = new Integer(n);

        values[1] = new Integer(n * n);

        final int COUNT = 25000;

        for (int i = 1; i <= COUNT; i++) {

            String s = fmt.format(values);

            System.out.print(s);

        }

   }

}

这些程序产生同样的输出。运行时间是:

 format1  1.3 format2  1.8 format3  7.8

或者说最慢的和最快的大约是6比1。如果格式没有预编译第三种方法将更慢,使用静态的方法代替:

方法 4

MessageFormat.format(String, Object[])

 

import java.text.*;

 

public class format4 {

   public static void main(String args[]) {

        String fmt = "The square of {0} is {1}\n";

        Object values[] = new Object[2];

        int n = 5;

        values[0] = new Integer(n);

        values[1] = new Integer(n * n);

        final int COUNT = 25000;

        for (int i = 1; i <= COUNT; i++) {

            String s = MessageFormat.format(fmt, values);

            System.out.print(s);

        }

   }

}

这比前一个例子多花费1/3的时间。

第三个方法比前两种方法慢很多的事实并不意味着你不应该使用它,而是你要意识到时间上的开销。

在国际化的情况下信息格式化是很重要的,关心这个问题的应用程序通常从一个绑定的资源中读取格式然后使用它。

posted @ 2018-08-06 23:36  borter  阅读(108)  评论(0编辑  收藏  举报