SimpleDateFormat三种不同的使用方法
这里总结一下SimpleDateFormat的三种用法不同的性能对比结果。
虽然SimpleDateFormat性能最差,线程不安全,但是一些老旧的系统还是有那么多的人用,这里就简单对比一下性能差异
代码
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
@ApiOperation("SimpleDateFormat-获取当前时间戳")
@ApiResponses({
@ApiResponse(code = 200, message = "OK", response= R.class),
})
@RequestMapping(value = "/SimpleDateFormat", method = RequestMethod.GET)
public String SimpleDateFormatCase(){
long startTime = System.currentTimeMillis();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
String date = sdf1.format(System.currentTimeMillis());
log.info("解析时间耗时:" + (System.currentTimeMillis() - startTime) + "ms");
return date;
}
@ApiOperation("SimpleDateFormat-获取当前时间戳2-复用SimpleDateFormat")
@ApiResponses({
@ApiResponse(code = 200, message = "OK", response= R.class),
})
@RequestMapping(value = "/SimpleDateFormat2", method = RequestMethod.GET)
public String SimpleDateFormatCase2(){
long startTime = System.currentTimeMillis();
String date = sdf.format(System.currentTimeMillis());
log.info("解析时间耗时:" + (System.currentTimeMillis() - startTime) + "ms");
return date;
}
@ApiOperation("SimpleDateFormat-获取当前时间戳3-使用线程锁")
@ApiResponses({
@ApiResponse(code = 200, message = "OK", response= R.class),
})
@RequestMapping(value = "/SimpleDateFormat3", method = RequestMethod.GET)
public String SimpleDateFormatCase3(){
String date = DateFormatUtil.formatDateTime(new Date());
return date;
}
DateFormatUtil.java
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 初始化日期格式的simpleDateFormat
*/
private static final ThreadLocal<SimpleDateFormat> DATE = new ThreadLocal<SimpleDateFormat>() {
@Override
protected synchronized SimpleDateFormat initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
private static SimpleDateFormat getDateTimeFormat() {
return DATE_TIME.get();
}
/**
* 将日期时间格式化为字符串
*
* @param date Date类型的日期
* @return 格式化后的字符串日期
*/
public static String formatDateTime(Date date) {
return getDateTimeFormat().format(date);
}
压测方式
直接用jmeter发压,10并发,发压100s,服务器监控用sar命令简单监控(也不是什么很复杂的业务,第三方监控组件没必要)
模型1结果
TPS:111.3笔/s,RT:88ms,CPU:37.1%
模型2结果
TPS:115笔/s,RT:86ms,CPU:20.25%
模型3结果
TPS:116笔/s,RT:85ms,CPU:12.92%
结果统计
模型 | TPS | 响应时间 | 90%Line | 95%Line | 99%Line | 资源消耗 |
---|---|---|---|---|---|---|
1 | 111.3 | 88 | 121 | 149 | 210 | 37.01% |
2 | 115 | 86 | 115 | 139 | 204 | 20.25% |
3 | 116 | 85 | 110 | 125 | 203 | 12.92% |
可以显而易见的看到TPS和RT其实相差不多的,主要还是应用资源消耗相差较大。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。