java bigdecimal 除100,将BigDecimal乘以100哪种方法更好?
Here I have a question when using Java BigDecimal.
Which way will be better when I want to multiply 100 for a object of BigDecimal.
multiply 10 twice;
movePointRight(2);
scaleByPowerOfTen(2);
any other way? please show me if there is.
BTW, it will be used for commercial calculation, so I'm considering the precision rather than the speed.
解决方案
Option 3 is the fastest. Options 1 and 2 are roughly the same (option one being to multiply by ten twice). Multiplying by 100 instead gets up near the speed of option 3.
Here's my test code:
import java.math.BigDecimal;
public class TestingStuff {
public static void main(String[] args){
BigDecimal d2 = new BigDecimal(0); // to load the big decimal class outside the loop
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++) {
BigDecimal d = new BigDecimal(99);
d2 = d.movePointRight(2);
}
long end = System.currentTimeMillis();
System.out.println("movePointRight: " + (end - start));
BigDecimal ten = new BigDecimal(10);
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++) {
BigDecimal d = new BigDecimal(99);
d2 = d.multiply(ten).multiply(ten);
}
end = System.currentTimeMillis();
System.out.println("multiply: " + (end - start));
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++) {
BigDecimal d = new BigDecimal(99);
d2 = d.scaleByPowerOfTen(2);
}
end = System.currentTimeMillis();
System.out.println("scaleByPowerOfTen: " + (end - start));
}
}
Of course you could just try the various options yourself in your own code. If you can't measure the difference, then why are you optimizing?
作者:流年二十春
来源链接:https://blog.csdn.net/weixin_34043312/article/details/118828217
版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。
2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。