是否有非分配方式来获取两个 LocalDateTime 点之间的差异?

Is there a non-allocating way to get the difference between two LocalDateTime points?

我很理解为什么两个 LocalDateTime 实例之间的差异表示为周期而不是持续时间,但我找不到 Period 是 class 而不是结构的原因.

我正在帮助移植一个做了很多这样的代码库:

DateTime t1;
DateTime t2;
TimeSpan diff = t2-t1;


// After port, with a surprising allocation
LocalDateTime t1;
LocalDateTime t2;
Period diff = t2-t1;

这似乎有点 perf/GC 陷阱,我很好奇为什么 Period 是 class 而不是结构?

Period 成为 class 的主要原因是它会很大 - 它有 6 个 long 字段和 4 个 int 字段。那将是 64 个字节 - 作为方法参数等传递的太多了。虽然 Noda Time 中的其他一些结构是 "pretty big" 它们不是 that 大。

但值得注意的是,这两段代码做的事情完全不同。 TimeSpan 的 Noda Time 不是 Period;它是 Duration,其中 一个结构。如果您不需要日历计算,您可能需要考虑将您的两个 LocalDateTime 值转换为 UTC 中的 Instant 值(或避免使用 LocalDateTime 开始),然后取这两个瞬间之间的差异。

在内部,有一些非分配的方法可以在日期之间获取 "the number of days",例如......我们可以 可能 公开公开类似的东西,但我认为值得首先进行基准测试以证明这确实很重要。 (GC 非常擅长收集非常临时的对象。当然,它不是免费的 - 但我认为代码必须做很少 other 才能成为一个主要因素.)