Question

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?

Thanks.

Was it helpful?

Solution

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.

OTHER TIPS

Using ZERO doesn't create a new object or require any parsing. Definitely the way to go.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top