有关Java中日期格式化的效率实录

java中格式化日期为固定格式的字符串,无外乎有两种方法:DateFormat 和String.format(JDK1.5+)

但是哪个方法效率更高呢?本人做了一个实验,发现了一个很有趣的现象。

当系统第一次使用SimpleDateFormat进行格式化日期对象的时候,消耗资源是比较大的。而第一次使用之后,每次再使用该对象甚至是该类不同的对象的同一个方法时,又会极大的节省时间。而String.format虽然也是存在第一次使用时资源消耗较大,但是从第二次开始,资源消耗减少的量却不是很明显了。

总结:第一次使用两种方法时SimpleDateFormat方法效率很低,耗费时间大概是String.format的10倍左右。

          从第二次开始,SimpleDateFormat效率提高1000倍左右,String.format提高10倍左右.消耗时间只占String.format的1/10.

          简单计算:如果系统使用日期格式化超过100次,就应该使用SimpleDateFormat,否则就应该使用String.format

PS:无论第二次使用SimpleDateFormat时是不是new了一个新的format对象,效率变化并不明显。

附源代码:

public static void main(String[] args) {
  int count = 1;
  long start = System.nanoTime();
  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  for(int i=0;i<count;i++) {
   sf.format(new Date());
  }
  System.out.println("ecllapsed:"+(System.nanoTime()-start));
  
  start = System.nanoTime();
  for(int i=0;i<count;i++) {
   String.format("%1$tF %1$tT", new Date());
  }
  System.out.println("ecllapsed:"+(System.nanoTime()-start));
  
  start = System.nanoTime();
  count = 1;
  for(int i=0;i<count;i++) {
   sf.format(new Date());
  }
  System.out.println("ecllapsed:"+(System.nanoTime()-start));
  start = System.nanoTime();
  for(int i=0;i<count;i++) {
   String.format("%1$tF %1$tT", new Date());
  }
  System.out.println("ecllapsed:"+(System.nanoTime()-start));
 }

猜你喜欢

转载自coolwhy1.iteye.com/blog/1885018