是否应将 org.joda.time.DateTimeZone 声明为 class 中的静态字段,而不是每次都创建新实例

Should org.joda.time.DateTimeZone be declared as static field in a class instead of creating new instance each time

是否应将 org.joda.time.DateTimeZone 定义为 class 中的 static 而不是每次需要时都创建一个新实例,特别是当我们始终使用同一时区时。

DateTimeZone 是线程安全且不可变的,因此每次都创建一个新实例没有意义。我的想法对吗?

要添加更多细节,目前我的 class 在我的 class 的构造函数中创建了一个 DateTimeZone 对象,总是针对同一时区,所以我想为什么不创建它static 而不是每次都创建一个新对象。

DateTimeZone is thread-safe and immutable, and all subclasses must be as well.

api

是的。它可以声明为静态字段。

做不做,要看你的class和整个项目的设计。请参阅 here 为什么静态字段可能是邪恶的。

是的,我认为您可以将 is 创建为 static 字段 - link in 会告诉您这样做可能存在的缺点(例如,如果您想在不同的时区等等)。

但如果您关心的是性能和内存使用,我不会太担心。 Joda-Time 似乎使用了 DateTimeZone 个对象的内部缓存:

DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTimeZone other = DateTimeZone.forID("Europe/London");
System.out.println(zone == other); // true

上面的代码打印出true,这意味着两者是同一个对象。

当然这是一个实现细节(我正在使用 Joda-Time 2.9.9)并且依赖这些细节是不好的,因为这些东西可能会改变。

无论如何,如果你确定这个时区永远不会改变,你可以static。如果以后有可能不止一个,那就不要(我不会)。