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.