Duration.between 对比 ChronoUnit.between

Duration.between vs ChronoUnit.between

这两种方法是否等同?

版本 1:

var diff = Duration.between(begin, end).toHours();

版本 2;

var diff = ChronoUnit.HOURS.between(begin, end);

是否存在隐含差异?如果是,我更喜欢哪一个?

看来这两个方法最终都调用了Temporal#until

var diff = Duration.between(begin, end).toHours();

Duration#between
\
 Temporal#until (used twice but some branching go for another implementation)

var diff = ChronoUnit.HOURS.between(开始, 结束);

ChronoUnit.HOURS#between
\
 Temporal#until (it is the only method underlying)

打开 JDK 15

时的分析实现

A) Duration.between(开始, 结束).toHours();

Duration.between(begin, end) 第一次来电

long until(Temporal endExclusive, TemporalUnit unit); //called with unit of NANOS or SECONDS if first one fails

然后解析差异以创建一个 Duration 基于已计算的纳米(如果纳米计算失败则为秒)

public static Duration between(Temporal startInclusive, Temporal endExclusive) {
        try {
            return ofNanos(startInclusive.until(endExclusive, NANOS));
        } catch (DateTimeException | ArithmeticException ex) {
            long secs = startInclusive.until(endExclusive, SECONDS);
            long nanos;
            try {
                nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
                if (secs > 0 && nanos < 0) {
                    secs++;
                } else if (secs < 0 && nanos > 0) {
                    secs--;
                }
            } catch (DateTimeException ex2) {
                nanos = 0;
            }
            return ofSeconds(secs, nanos);
        }

然后你必须调用 toHours() 然后将创建的 Duration 对象解析为 return 小时

B) ChronoUnit.HOURS.between(开始, 结束);

直接调用

long until(Temporal endExclusive, TemporalUnit unit);

//But instead of the implementation before, now it is called with unit of HOURS directly

直接 return 小时数。

实现比较

两者的工作方式相同(至少在几个小时内)并给出相同的结果。

但是对于 A 似乎我们有一些不必要的来回转换。

解决方案 B 似乎很简单,没有任何我们不需要的转换

回答

我会选择 B 因为效率更高