deamon
deamon

Reputation: 92509

Why to avoid biginteger instantiation in Java

There is a PMD rule saying one should avoid to instantiate BigInteger or BigDecimal if there is a predefined constant.

BigInteger.ZERO

// instead of

new BigInteger(0)

Would there be any other advantage than saving a few bytes?

Upvotes: 5

Views: 2822

Answers (5)

tcb
tcb

Reputation: 2814

Instead of creating a new object with new BigInteger you'd better use one static object which is created once when the BigInteger class is loaded. It is also true for using valueOf of all wrapper types.

Upvotes: 1

mre
mre

Reputation: 44250

By using cached values, it is likely to yield significantly better space and time performance.

Upvotes: 1

andypandy
andypandy

Reputation: 1117

Possibly performance, if you are instantiating a lot of 0s. An alternative for long/int argument is

BigInteger.valueOf(0)

which returns BigInteger.ZERO when argument is 0

Upvotes: 2

ratchet freak
ratchet freak

Reputation: 48216

it avoids the allocation of those few bytes and the need to collect them back later

in a tight loop that can matter

Upvotes: 6

michael667
michael667

Reputation: 3260

Yes, saving a few JVM instructions.

Upvotes: 2

Related Questions