Increasing Java's BigInteger performance

后端 未结 4 475
清歌不尽
清歌不尽 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:33

    The computation itself should not take so long. The string creation may take a while, however.

    This program (Kudos to OldCurmudgeon and https://stackoverflow.com/a/8583188/823393 ) takes approximately 3.9 seconds on a Core I7, 3GHz, Java 7/21, when started with -Xmx1000m -sever:

    import java.lang.reflect.Constructor;
    import java.lang.reflect.Method;
    
    public class FastBigInteger
    {
        public static void main(String[] args)
        {
            try
            {
                Class c = Class.forName("java.math.MutableBigInteger");
                Constructor con = c.getDeclaredConstructor(int.class);
                con.setAccessible(true);
                Object i = con.newInstance(1);
                Method m = c.getDeclaredMethod("mul", new Class[] { int.class, c });
                m.setAccessible(true);
                long before = System.nanoTime();
                for (int z = 2; z < 99999; ++z)
                {
                    m.invoke(i, z, i);
                }
                long after = System.nanoTime();
                System.out.println("Duration "+(after-before)/1e9);
    
                String s = i.toString();
                int n = s.length();
                int lineWidth = 200;
                for (int j=0; j

    After printing the duration for the actual computation, it takes quite a while until it finished creating the string, but this should hardly be taken into account here.

    This is still not a sensible benchmark, but shows that there is at least no problem with the computation itself.

    But admittedly, when using only BigInteger instead of this MutableBigInteger hack, it takes appx. 15 seconds, which is rather poor compared to the C++ implementation.

提交回复
热议问题