views:

2266

answers:

4

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.

+12  A: 

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 BigInteger.ZERO. The first time it is used, it would call BigInteger("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 BigInteger.ZERO with no runtime penalty.

Greg Hewgill
I would remove the word "essentially" - it IS a predefined constant.
Bob Cross
Good call, thanks.
Greg Hewgill
new BigDecimal("0") creates a new object instance every time but BigDecimal.ZERO does not create new instances.
Juha Syrjälä
There is no need to create a singleton if you just create public static final in a final class called along the lines of "Constants", and just use that.
Spencer K
@Spencer that's the same thing
wds
+5  A: 

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

Jon Skeet
+1  A: 

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.

Allain Lalonde
There'd be a difference anyway, as calling new BigDecimal("0") will create a new object each time.
Jon Skeet
Can't argue that. I was just curious to know how large a penalty not using ZERO would be. Turns out it's substantial since the constructor for BigDecimal is pretty heavy.
Allain Lalonde
A: 

Before talking about runtime penalties make sure that this piece of code matters. Setup profiling and measure the complete use case.

Nevertheless prefer Bigdecimal.ZERO as it's checked at compile time wheres you can accidently type new Bigdecimal("9") which the compile will eat but like will cause bugs into your system.

ordnungswidrig
You could say this about any number.
Robert L