问题描述
我为生活编写货币交易应用程序,所以我必须使用货币值(遗憾的是,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
, b
和 c
是定点值)。然而,问题在于此(1 / b)
。我不能使用定点算术,因为没有固定点。并且 BigDecimal结果= 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倍的性能提升。我发现其他方面非常出色,它具有任意精度的算术,但它甚至比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吗?它不是10x,但仍然是。
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性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!