问题
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?
回答1:
it avoids the allocation of those few bytes and the need to collect them back later
in a tight loop that can matter
回答2:
Yes, saving a few JVM instructions.
回答3:
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
回答4:
By using cached values, it is likely to yield significantly better space and time performance.
回答5:
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.
来源:https://stackoverflow.com/questions/7674391/why-to-avoid-biginteger-instantiation-in-java