java yyyymmdd 的date,在Java中解析YYYYMMdd日期的最快方式

When parsing a YYYYMMdd date, e.g. 20120405 for 5th April 2012, what is the fastest method?

int year = Integer.parseInt(dateString.substring(0, 4));

int month = Integer.parseInt(dateString.substring(4, 6));

int day = Integer.parseInt(dateString.substring(6));

vs.

int date = Integer.parseInt(dateString)

year = date / 10000;

month = (date % 10000) / 100;

day = date % 100;

mod 10000 for month would be because mod 10000 results in MMdd and the result / 100 is MM

In the first example we do 3 String operations and 3 "parse to int", in the second example we do many things via modulo.

What is faster? Is there an even faster method?

解决方案

As you see below, the performance of the date processing only is relevant when you look at millions of iterations. Instead, you should choose a solution that is easy to read and maintain.

Although you could use SimpleDateFormat, it is not reentrant so should be avoided. The best solution is to use the great Joda time classes:

private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()

.appendYear(4,4).appendMonthOfYear(2).appendDayOfMonth(2).toFormatter();

...

Date date = DATE_FORMATTER.parseDateTime(dateOfBirth).toDate();

If we are talking about your math functions, the first thing to point out is that there were bugs in your math code that I've fixed. That's the problem with doing by hand. That said, the ones that process the string once will be the fastest. A quick test run shows that:

year = Integer.parseInt(dateString.substring(0, 4));

month = Integer.parseInt(dateString.substring(4, 6));

day = Integer.parseInt(dateString.substring(6));

Takes ~800ms while:

int date = Integer.parseInt(dateString);

year = date / 10000;

month = (date % 10000) / 100;

day = date % 100;

total += year + month + day;

Takes ~400ms.

However ... again... you need to take into account that this is after 10 million iterations. This is a perfect example of premature optimization. I'd choose the one that is the most readable and the easiest to maintain. That's why the Joda time answer is the best.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值