在产品的性能优化过程中发现JDK的日期类Calendar使用起来太慢,于是找了替代方案,惊喜的发现Joda-time类库,提供的API功能丰富,关键的是性能要比JDK的Calendar要高出许多。
1)日期的实例化//构造方法有很多,对比Calendar类,实例化性能高出一倍有余
//如果带上时间戳作为构造函数的性能会更高
DateTime dt=new DateTime();
2)日期的格式化//实例化formatter对象
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
//创建日期,这里也可以用joda的DateTime对象
Date d = new Date();
fdf.format(d);
3)日期的解析//实例化formatter对象
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
//解析日期
fdf.parse("2016-04-23 11:23:45.234");
以上是几个主要的API,更多的API还请自行研究,一定会有惊喜。
参考以下测试代码:@Test
public void testCreateCalendar() {
long start = System.currentTimeMillis();
for (int i = 0; i
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, (int) start);
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void testCreateJodaTime() {
long start = System.currentTimeMillis();
for (int i = 0; i
new DateTime(start);
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void testParseDate() throws ParseException {
long start = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
for (int i = 0; i
sdf.parse("2016-04-23 11:23:45.234");
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void testJodaParseDate() throws ParseException {
long start = System.currentTimeMillis();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
for (int i = 0; i
fdf.parse("2016-04-23 11:23:45.234");
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void testFormatDate() throws ParseException {
long start = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date d = new Date();
for (int i = 0; i
sdf.format(d);
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void testJodaFormatDate() throws ParseException {
long start = System.currentTimeMillis();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
Date d = new Date();
for (int i = 0; i
fdf.format(d);
}
System.out.println(System.currentTimeMillis() - start);
}
综合比较下来,joda-time的性能差不多是calendar的1.5-2倍左右。