Ankit Kumar
Ankit Kumar

Reputation: 403

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

Upvotes: 15

Views: 79405

Answers (3)

Wathsala Karunathilake
Wathsala Karunathilake

Reputation: 1508

You can use the following constant to initialize BigDecimal.

 BigDecimal.ZERO
 BigDecimal.ONE
 BigDecimal.Ten
BigDecimal average = BigDecimal.ZERO;

Upvotes: 4

Tony Giaccone
Tony Giaccone

Reputation: 511

You just need to show caution when using a decimal value in the initialization of a BigDecimal.

BigDecimal onePercentPlusABit = new BigDecimal(0.01);

is not equal to

BigDecimal onePercentExact = new BigDecimal("0.01");

and this:

BigDecimal(0.01).setScale(2, RoundingMode.HALF_UP);

is significantly slower than

BigDecimal("0.01");

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502825

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.

Upvotes: 24

Related Questions