Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
deamon Avatar asked Oct 06 '11 12:10

deamon


People also ask

Is BigInteger slow Java?

BigInteger is by far the slowest. Add: BigInt is fastest due to its mutability.

Why do we use BigInteger in Java?

BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

What is the difference between long and BigInteger in Java?

BigInteger is capable of holding far bigger numbers than Long.

What is the difference between BigDecimal and BigInteger in Java?

The main difference between the BigInteger and BigDecimal is that BigInteger supports arbitrary-precision integers and BigDecimal is for arbitrary-precision fixed-point numbers.


2 Answers

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

in a tight loop that can matter

like image 108
ratchet freak Avatar answered Sep 28 '22 14:09

ratchet freak


Yes, saving a few JVM instructions.

like image 40
michael667 Avatar answered Sep 28 '22 14:09

michael667