Why to avoid biginteger instantiation in Java

偶尔善良 提交于 2019-12-12 11:05:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!