每一次时间格式化的时候都会去手动new SimpleDateFormat,每一次new都是一次较大的性能开销,因此想到的是用static的形式来提高性能。由于SimpleDateFormat是线程不安全的,因此可以借助ThredLocal来实现线程安全。
代码如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatUtil {
/**
* 日期格式
*/
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 日期时间格式
*/
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 初始化日期格式的simpleDateFormat
*/
private static final ThreadLocal<SimpleDateFormat> DATE = new ThreadLocal<SimpleDateFormat>() {
@Override
protected synchronized SimpleDateFormat initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
/**
* 初始化日期时间格式的SimpleDateFormat
*/
private static final ThreadLocal<SimpleDateFormat> DATE_TIME = new ThreadLocal<SimpleDateFormat>() {
@Override
protected synchronized SimpleDateFormat initialValue() {
return new SimpleDateFormat(DATE_TIME_FORMAT);
}
};
/**
* 将日期格式化为字符串
*
* @param date Date类型的日期
* @return 格式化后的字符串日期
*/
public static String formatDate(Date date) {
return getDateFormat().format(date);
}
/**
* 将日期时间格式化为字符串
*
* @param date Date类型的日期
* @return 格式化后的字符串日期
*/
public static String formatDateTime(Date date) {
return getDateTimeFormat().format(date);
}
/**
* 将字符串格式化为日期
*
* @param date 字符串日期
* @return Date类型的日期
*/
public static Date parseDate(String date) {
try {
return getDateFormat().parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 将字符串格式化为日期时间
*
* @param date 字符串日期
* @return Date类型的日期
*/
public static Date parseDateTime(String date) {
try {
return getDateTimeFormat().parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private static SimpleDateFormat getDateFormat() {
return DATE.get();
}
private static SimpleDateFormat getDateTimeFormat() {
return DATE_TIME.get();
}
}
测试100万,500万,1000万循环不断的format时间测试性能:
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
simpleDateFormat.format(new Date());
}
long end = System.currentTimeMillis();
System.out.println("new SimpleDateFormat耗时:" + (end - start));
//测试DateFormatUtil
long start2 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
DateFormatUtil.formatDateTime(new Date());
}
long end2 = System.currentTimeMillis();
System.out.println("DateFormatUtil耗时:" + (end2 - start2));
}
100万的时候
new数据的方式 ,耗时: 2841、2470 、2672
ThreadLocal的方式,耗时:1286、1236、1362
500万的时候
new数据的方式 ,耗时: 7566、7445 、7537
ThreadLocal的方式,耗时:4165、4282、4122
100万的时候
new数据的方式 ,耗时: 12818、13513
ThreadLocal的方式,耗时:6038、6002
性能是有所提升的。