这两种方法是等价的吗?
版本1:
var diff = Duration.between(begin, end).toHours();版本2;
var diff = ChronoUnit.HOURS.between(begin, end);有什么隐含的区别吗?如果是,我应该选择哪一种?
发布于 2021-02-17 19:09:37
开放JDK 15的分析实现
A) Duration.between(begin,end).toHours();
Duration.between(begin, end)优先呼叫
long until(Temporal endExclusive, TemporalUnit unit); //called with unit of NANOS or SECONDS if first one fails然后分析差异,根据已计算的nanos创建一个Duration (如果nanos计算失败,则创建秒)。
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对象以返回小时数。
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直接返回时间一样长的时间。
实现的比较
两者的工作方式相同(至少几个小时),结果也是一样的。
但是对于A,,我们似乎有一些不需要的来回转换。
解决方案B看起来很直接,没有任何我们不需要的转换
答案
我会选择B作为更有效率的
发布于 2021-02-17 18:47:13
这两种方法似乎最终都调用了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)https://stackoverflow.com/questions/66247921
复制相似问题