Is there a difference between BigDecimal(“0”) and BigDecimal.ZERO?

后端 未结 4 1406
忘了有多久
忘了有多久 2020-12-30 21:56

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 th

4条回答
  •  伪装坚强ぢ
    2020-12-30 22:40

    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.

    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.

提交回复
热议问题