I have to declare and initialize BigDecimal wrapper object several times in project. Then which is better approach either by java Code:
BigDecimal num=new BigDecimal("123");
or in NumberUtils
class there is already a static method available as
public static BigInteger createBigInteger(String str) {
if (str == null) {
return null;
}
return new BigInteger(str);
}
BigDecimal num=NumberUtils.createBigInteger("123");
Plese tell me, which is better approach as we compared performance wise(memory and speed).
The various approaches to solving the How To Initialize Bigdecimal In Java problem are outlined in the following code. BigDecimal d1 = BigDecimal. valueOf(0.34); BigDecimal d2 = BigDecimal. valueOf(0.12); BigDecimal d3 = d1.
valueOf() has the more intuitive behaviour, while new BigDecimal(d) has the more correct one. Try both and see the difference.
Just like the other Number classes (Integer, Long, Double etc.), BigDecimal provides operations for arithmetic and comparison operations. It also provides operations for scale manipulation, rounding and format conversion. It does not overload the the arithmetic (+, -, /, *) or logical (>. < etc) operators.
If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.
Well clearly createBigInteger
is doing more work - it's checking for nullity, when you know the argument value won't be null anyway. That's only a tiny, tiny bit of extra work though - almost certain to be irrelevant in reality.
I'd be surprised if this were really a performance concern anyway though - have you identified this to be a bottleneck in your code? If not, write the most readable code - which for me would be the constructor call. Then identify what your performance requirements are, and test your whole system against them. If it's not performing well enough, write more tests or use a profiler to identify which areas are causing problems.
Another alternative would be to use the BigDecimal(int)
constructor - why bother parsing a string?
BigDecimal num = new BigDecimal(123);
If you wanted, you could even have this as a constant, so you could reuse the object:
private static final BigDecimal DEFAULT_FOOBAR_VALUE = new BigDecimal(123);
// In a method or whatever...
BigDecimal num = DEFAULT_FOOBAR_VALUE;
Aside from performance, I'd argue this is clearer as it indicates the reason for the constant.
You can use the following constant to initialize BigDecimal.
BigDecimal.ZERO
BigDecimal.ONE
BigDecimal.Ten
BigDecimal average = BigDecimal.ZERO;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With