Is it better approach to declare and initialize a bigdecimal number with "new" keyword or static method?

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).

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow