获取格式化字符串比使用Period / PeriodFormat更有效吗?

时间:2011-12-15 20:00:23

标签: java jodatime

我想知道从CPU时间的角度来看是否有更有效的方法:

/*
* Returns a string in the form of "n days, x hours, y minutes"
* */

public static String getFormattedDateDifference(DateTime startDate, DateTime endDate) {
    Period p = new Period(startDate, endDate,
            PeriodType.standard().withSecondsRemoved().withMillisRemoved());
    return PeriodFormat.getDefault().print(p);
}

1 个答案:

答案 0 :(得分:0)

这可能吗?

private static final Pattern PATTERN = Pattern.compile(", $");

public static String getFormattedDateDifference(final DateTime startDate,
    final DateTime endDate)
{
    // This variable will ultimately contain the number of days
    long days = endDate.getMillis() - startDate.getMillis();

    final long hours, minutes;

    days /= 60000; // Forget seconds and milliseconds

    minutes = days % 60;  days /= 60;

    hours = days % 24; days /= 24;

    final StringBuilder sb = new StringBuilder();

    if (days != 0) {
        sb.append(days).append(" day");
        if (days > 1)
            sb.append('s');
        sb.append(", ");
    }
    if (hours != 0) {
        sb.append(hours).append(" hour");
        if (hours > 1)
            sb.append('s');
        sb.append(", ");
    }
    if (minutes != 0) {
        sb.append(minutes).append(" minute");
        if (minutes > 1)
            sb.append('s');
        sb.append(", ");
    }

    return PATTERN.matcher(sb.toString()).replaceFirst("");
}

使用这个简单的main(),它显示了超过两倍的加速:

public static void main(final String... args)
{
    final DateTime d = DateTime.now();

    final DateTime d2 = d.minus(Days.days(1)).minus(Minutes.minutes(3));

    long start, end;

    final int count = 5000;
    int i;

    start = System.currentTimeMillis();
    for (i = 0; i < count; i++)
        getFormattedDateDifference(d2, d); // <-- the original implementation
    end = System.currentTimeMillis();

    System.out.println(end - start);

    start = System.currentTimeMillis();
    for (i = 0; i < count; i++)
        getFormattedDateDifference2(d2, d); // <-- the implementation above
    end = System.currentTimeMillis();

    System.out.println(end - start);

    System.exit(0);
}

原始功能为383 ms,我的为150 ms。