Increasing Java's BigInteger performance

后端 未结 4 462
清歌不尽
清歌不尽 2021-02-04 09:46

How to increase performance of Java\'s Big Integer?

For example, this factorial program:

import java.math.*;
class Fac {
  public static void main(String         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 10:51

    Start with:

    import java.math.*;
    class Fac {
      public static void main(String[] args) {
        BigInteger i = BigInteger.ONE;
        BigInteger maxValue = BigInteger.valueOf(99999);
    
        for(BigInteger z=BigInteger.valueOf(2); z.compareTo(maxValue) != 0;) {
          i = i.multiply(z);
          z = z.add(BigInteger.ONE);
        }
    
        System.out.println( i );
      }
    }
    

    .valueOf source

    1081    public static BigInteger More ...valueOf(long val) {
    1082        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
    1083        if (val == 0)
    1084            return ZERO;
    1085        if (val > 0 && val <= MAX_CONSTANT)
    1086            return posConst[(int) val];
    1087        else if (val < 0 && val >= -MAX_CONSTANT)
    1088            return negConst[(int) -val];
    1089
    1090        return new BigInteger(val);
    1091    }
    

    It will create a new BigInteger everytime since MAX_CONSTANT is 16.


    I think it could go slower because the GC starts to collect some older BigInteger instances but anyway you should always use int and long.. here BigInteger is not really needed.

    After your last test i think we can be sure it could be caused by the GC.

提交回复
热议问题