Java BigDecimal("0") 和 BigDecimal.ZERO 之间有区别吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/269669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a difference between BigDecimal("0") and BigDecimal.ZERO?
提问by MattGrommes
Either for comparisons or initialization of a new variable, does it make a difference which one of these you use?
对于新变量的比较或初始化,您使用其中的哪一个会有所不同吗?
I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter?
我知道 BigDecimal.ZERO 是 1.5 的功能,所以这是一个问题,但假设我使用的是 1.5 有关系吗?
Thanks.
谢谢。
采纳答案by Greg Hewgill
BigDecimal.ZERO
is a predefined constant and therefore doesn't have to be evaluated from a string at runtime as BigDecimal("0")
would be. It will be faster and won't require creation of a new object.
BigDecimal.ZERO
是一个预定义的常量,因此不必像在运行时那样从字符串中求值BigDecimal("0")
。它会更快,并且不需要创建新对象。
If your code needs to run on pre-1.5, then you can use the (much maligned) Singleton pattern to create an object equivalent to BigDecimal.ZERO
. The first time it is used, it would call BigDecimal("0")
to create a zero object, and return that object on subsequent calls. Otherwise, if your code is running on a 1.5 system, your singleton object can just return BigDecimal.ZERO
with no runtime penalty.
如果您的代码需要在 1.5 之前的版本上运行,那么您可以使用(备受诟病的)单例模式来创建一个等效于BigDecimal.ZERO
. 第一次使用时,它会调用BigDecimal("0")
创建一个零对象,并在后续调用中返回该对象。否则,如果您的代码在 1.5 系统上运行,您的单例对象可以直接返回BigDecimal.ZERO
而不会造成运行时损失。
回答by Jon Skeet
Using ZERO doesn't create a new object or require any parsing. Definitely the way to go.
使用 ZERO 不会创建新对象或需要任何解析。绝对是要走的路。
回答by Allain Lalonde
Out of curiosity I checked to constructor for BigDecimal and it doesn't have any optimizations for the "0" string. So definitely yes, there's a difference.
出于好奇,我检查了 BigDecimal 的构造函数,它没有对“0”字符串进行任何优化。所以肯定是的,有区别。
回答by ordnungswidrig
Before talking about runtime penalties, make sure that this piece of code matters. Set up profiling and measure the complete use case.
在谈论运行时惩罚之前,请确保这段代码很重要。设置分析并衡量完整的用例。
Nevertheless, prefer Bigdecimal.ZERO
as it's checked at compile time whereas you can accidentally type new BigDecimal("9")
, which the compiler will accept, but which will cause bugs into your application.
然而,更喜欢Bigdecimal.ZERO
在编译时检查它,而您可能会不小心键入new BigDecimal("9")
,编译器会接受,但这会导致您的应用程序出现错误。