Calendar.getInstance() 通过 'warm up' 调用提高了性能?

Calendar.getInstance() performance improvement with 'warm up' call?

我注意到如果我调用 Calendar.getInstance() 一次,在我真正需要 Calendar 实例之前,第二次调用的性能会提高。

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    // this block of code performs faster if the above code is included
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTimeInMillis(System.currentTimeMillis());

我正在从我的服务器获取自纪元以来的时间并用它初始化日历。然后将日历解析为小时、分钟、秒和毫秒,并将其传递给设置时间的本机函数。

我注意到,如果我首先实例化虚拟日历,节点之间的时钟差异为 2-5 毫秒,如果不实例化,则为 15-20 毫秒。

我正在测量从节点 A 到 B 的往返时间和数据包传输时间,反之亦然。我在请求-响应事务中的节点之间共享时间戳,并注意到当没有 'warm up'.

时,这些时间戳会更加关闭

虽然我的测量结果可能有问题,但我通过 'warm up' 电话获得的行程时间值一直较小。

我正在查看 Calendar 的源代码,但我没有看到对此行为的任何解释。

日历实现中是否有任何内容会影响后续调用的初始化性能?

Average from A to B: 21,4 

Average from A to B: 15,14 

Average from A to B: 14,84 

Average from A to B: 14,07 

有热身电话

Average from A to B: 11,8 

Average from A to B: 4,77 

Average from A to B: 4,54 

Average from A to B: 4,4

更新

提前单次调用本机函数似乎也受益于性能改进,因为时差变为 0.8 - 1 毫秒。

Is there anything in calendar implementation that could affect performance of initialization with subsequent calls ?

这是Calendar#getInstance()的代码:

public static Calendar getInstance()
{
    Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
    cal.sharedZone = true;
    return cal;
}

TimeZone#getDefaultRef()的代码是:

static TimeZone getDefaultRef() {
    TimeZone defaultZone = getDefaultInAppContext();
    if (defaultZone == null) {
        defaultZone = defaultTimeZone;
        if (defaultZone == null) {
            // Need to initialize the default time zone.
            defaultZone = setDefaultZone();
            assert defaultZone != null;
        }
    }
    // Don't clone here.
    return defaultZone;
}

Locale.getDefault(Locale.Category.FORMAT)之一:

public static Locale getDefault(Locale.Category category) {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    switch (category) {
    case DISPLAY:
        if (defaultDisplayLocale == null) {
            initDefault(category);
        }
        return defaultDisplayLocale;
    case FORMAT:
        if (defaultFormatLocale == null) {
            initDefault(category);
        }
        return defaultFormatLocale;
    default:
        assert false: "Unknown Category";
    }
    return getDefault();
}

注意这两种方法如何检查已经初始化的变量,例如静态变量 defaultTimeZonedefaultFormatLocale。至少这有望提高第二次调用 Calendar#getInstance().

的性能