恩来小平 Dev Engineer

jdk8日期类性能测试

2018-11-09
恩来小平

Instant start = Instant.now();
//code here
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
System.out.println(sdf.format(date));
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
System.out.println(timeElapsed);

执行1000000次

Case I

Code with Date API prior to Java 8 1603ms

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String s = sdf.format(date);

Code with Java 8 Date Time API 585ms

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
String dateStr = date.format(format);

Case II

Code with Date API prior to Java 8 1811ms

SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Calendar cal = Calendar.getInstance();
int lCurrentTime = Integer.parseInt(sdf.format(cal.getTime()));

Code with Java 8 Date Time API 571ms

int time = Integer.parseInt(LocalTime.now().format(
        DateTimeFormatter.ofPattern("HHmmss")));

Case III

Code with Date API prior to Java 8 2057ms

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
Calendar cal = Calendar.getInstance();
String time = sdf.format(cal.getTime());

Code with Java 8 Date Time API 321ms

String time = LocalTime.now().toString();

Case IV

Code with Date API prior to Java 8 1249ms

DateFormat dateFormat = new SimpleDateFormat("yyyy");
Date lCreationDate = new Date();
String year = dateFormat.format(lCreationDate);

Code with Java 8 Date Time API 238ms

String year = String.valueOf(LocalDate.now().getYear());

Case V

Code with Date API prior to Java 8 310ms

GregorianCalendar gc = new GregorianCalendar();
int day = gc.get(GregorianCalendar.DAY_OF_YEAR);

Code with Java 8 Date Time API 242ms

int dayOfYear = LocalDate.now().getDayOfYear();

Case VI

Code with Date API prior to Java 8 1906ms

java.util.Date date= new java.util.Date();
String lFormatedTS = new SimpleDateFormat("yyyyMMddhhmmss").format(
        date.getTime());

Code with Java 8 Date Time API 785ms

String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern(
        "yyyyMMddhhmmss"));

Conclusion

Except for Case IV where a variance was seen in performance, in all other cases code with Java 8 API performed better than old Date time API.

Scenario Approximate performance gain in execution time with Date Time API of Java 8 in percentage
Case I 2.5 times faster
Case II 2.8 times faster
Case III 5.8 times faster
Case VI 6.5 times faster
Case V 1.3 times faster
Case VI 2.9 times faster

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦


Similar Posts

Content