BigInteger 占用大量内存

BigInteger cosumes a lot of memory

我要测试以下代码:

import java.math.BigInteger;
import java.util.Random;

public class TestBigInteger {

    public static void main(String[] args) {
        BigInteger bigInteger = BigInteger.probablePrime(32, new Random())
                .multiply(BigInteger.probablePrime(32, new Random()));
        BigInteger n = BigInteger.probablePrime(20, new Random());
        while (!Thread.interrupted()) {
            bigInteger.mod(n);
        }

    }
}

我从 jconsole 得到了以下图:

为什么会这样?如果我的 bigInteger 只有 64 位长度,为什么 mod 操作真的需要很多内存?

这不会保留大量内存,而是会产生大量垃圾。

    while (!Thread.interrupted()) {
        bigInteger.mod(n); // create a new objects each time.
    }

这个循环尽可能快地创建垃圾(还有一点 CPU 工作)因此你应该期望看到内存使用非常活跃。

Why mod operation takes really a lot of memory, if my bigInteger is only 64 bit length?

这会使内存使用率更高,因为 CPU 实际花在计算上的数量相对较少。如果您有更大的数字,与创建对象相比,使用 CPU 会花费更多时间。事实上,与它使用的 CPU 相比,它花费更多的时间来创建垃圾。

顺便说一句,我建议您使用 Java 6 中的 VisualVM 和 Java 7 中的 Java Mission Control,而不是 jconsole。

函数 BigInteger.mod 正在使用 BigInteger.remainder 函数,它创建了几个 MutableBigInteger 对象。

并且您通过调用创建了很多对象:

 while (!Thread.interrupted()) {
        bigInteger.mod(n); // create a new large object each time.
 }