BigDecimal.valueOf的性能(双d)

时间:2011-07-27 10:05:24

标签: java performance floating-point bigdecimal value-of

我有一段代码需要重复计算以下内容......

        double consumption = minConsumption + ( Math.random() * ( ( maxConsumption - minConsumption ) + 1 ) );
        currentReading = currentReading.add( BigDecimal.valueOf( consumption ) ).setScale( 2, RoundingMode.HALF_EVEN ).stripTrailingZeros();

这用于生成用于测试的随机信息。它看起来比我预期的要慢,我发现慢速部分是BigDecimal.valueOf( consumption )而且由于内部发生的Double.toString()调用而很慢。

总体要求是生成在最小值和最大值之间随机的消耗值。然后将其添加到currentReading以获得新的读数。

有什么办法可以改善这个性能吗?也许通过避免双重 - > BigDecimal转换。我需要将结果作为BigDecimal,但我不介意在此之前如何进行随机计算。

1 个答案:

答案 0 :(得分:7)

您可以创建一个移位两个位置的int值,即1234表示12.34,然后在创建BigDecimal时设置比例,而不是计算要舍入到两个小数位的double值。即将其除以100

double min = 100;
double max = 10000000;
{
    long start = 0;
    int runs = 1000000;
    for (int i = -10000; i < runs; i++) {
        if (i == 0)
            start = System.nanoTime();
        double consumption = min + (Math.random() * ((max - min) + 1));

        BigDecimal.valueOf(consumption).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
    long time = System.nanoTime() - start;
    System.out.printf("The average time with BigDecimal.valueOf(double) was %,d%n", time / runs);
}
{
    long start = 0;
    int runs = 1000000;
    int min2 = (int) (min * 100);
    int range = (int) ((max - min) * 100);
    Random rand = new Random();
    for (int i = -10000; i < runs; i++) {
        if (i == 0)
            start = System.nanoTime();
        int rand100 = rand.nextInt(range) + min2;
        BigDecimal bd = BigDecimal.valueOf(rand100, 2);
    }
    long time = System.nanoTime() - start;
    System.out.printf("The average time with BigDecimal.valueOf(long, int) was %,d%n", time / runs);

}

打印

The average time with BigDecimal.valueOf(double) was 557
The average time with BigDecimal.valueOf(long, int) was 18