如何处理 Java BigDecimal 性能? [英] What to do with Java BigDecimal performance?

查看:68
本文介绍了如何处理 Java BigDecimal 性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写货币交易应用程序是为了生活,所以我必须处理货币价值(遗憾的是 Java 仍然没有十进制浮点类型并且没有任何支持任意精度货币计算的东西).使用 BigDecimal!"——你可能会说.我做.但是现在我有一些代码,其中性能一个问题,而 BigDecimal 比 double 原语慢 1000 多倍(!).

I write currency trading applications for living, so I have to work with monetary values (it's a shame that Java still doesn't have decimal float type and has nothing to support arbitrary-precision monetary calculations). "Use BigDecimal!" — you might say. I do. But now I have some code where performance is an issue, and BigDecimal is more than 1000 times (!) slower than double primitives.

计算非常简单:系统所做的是多次计算a = (1/b) * c(其中a, bc 是定点值).然而,问题在于这个(1/b).我不能使用定点算法,因为没有定点.而 BigDecimal result = a.multiply(BigDecimal.ONE.divide(b).multiply(c) 不仅丑陋,而且缓慢.

The calculations are very simple: what the system does is calculating a = (1/b) * c many many times (where a, b and c are fixed-point values). The problem, however, lies with this (1/b). I can't use fixed point arithmetic because there is no fixed point. And BigDecimal result = a.multiply(BigDecimal.ONE.divide(b).multiply(c) is not only ugly, but sluggishly slow.

我可以用什么来代替 BigDecimal?我需要至少 10 倍的性能提升.我发现其他优秀的 JScience 库 具有任意精度算术,但它甚至比 BigDecimal 还要慢.

What can I use to replace BigDecimal? I need at least 10x performance increase. I found otherwise excellent JScience library which has arbitrary-precision arithmetics, but it's even slower than BigDecimal.

有什么建议吗?

推荐答案

也许你应该从用 a = c/b 替换 a = (1/b) * c 开始?不是 10 倍,但仍然是一些东西.

May be you should start with replacing a = (1/b) * c with a = c/b ? It's not 10x, but still something.

如果我是你,我会创建自己的类 Money,它会保存多头美元和多头美分,并在其中进行数学运算.

If I were you, I'd create my own class Money, which would keep long dollars and long cents, and do math in it.

这篇关于如何处理 Java BigDecimal 性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆