Increasing Java's BigInteger performance

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

    I have some clojure code calculating the 100 000th fibonacci number using big integers. Now this thread is not about clojure but as clojure runs on the JVM and I ran benchmarks on some of the existing big integer implementations I felt a comment here might be valuable.

    The algorithm when it is using the JVM BigInteger class (denoted by the xN literal syntax in clojure) looks as follows:

    (defn fibo [n]
      (loop [i n a 1N b 1N]
        (if (> i 0)
          (recur (dec i) b (+ a b))
          a)))
    

    I have re-implemented this using four big integer implementations and I ran benchmarks using the clojure criterium library which does warm ups and some statistical analysis to try to get to somewhat relevant numbers.

    Results on my 2,8 GHz Intel Core i7 macbook:

    • apfloat apint class - 964 ms
    • jvm BigInteger class - 130 ms
    • jscience LargeInteger class - 104 ms
    • huldra BigInt class - 60 ms

    now I realize this is all anecdotal and that we are only measuring addition here, but I would have to say that the huldra catch phrase "Outperforming BigInteger since 2015" seems pretty accurate in this case.

    Any comments with pointers to potential candidates for faster big int addition algorithms are much appreciated.

提交回复
热议问题