BigInteger耗费了大量的记忆

Ton*_*ony 3 java memory garbage-collection jconsole biginteger

我有以下代码来测试:

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);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我从jconsole得到了以下情节:

在此输入图像描述

为什么会这样?如果我bigInteger只有64位长度,为什么mod操作会占用大量内存?

Pet*_*rey 7

这并没有留下很多内存,而是产生了大量的垃圾.

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

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

如果我的bigInteger只有64位长度,为什么mod操作会占用大量内存?

这使得内存使用率更高,因为执行计算的实际CPU花费量相对较小.如果你有一个更大的数字,与创建对象相比,它将花费更多的时间来使用CPU.因为与使用的CPU相比,它花费更多时间来创建垃圾.

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