Why is factorial calculation much faster in Haskell than in Java

后端 未结 5 1928
终归单人心
终归单人心 2021-02-07 01:56

One of the programming problems I have come across involves calculation of factorials of large numbers (of numbers up to 10^5). I have seen a simple Haskell code which goes lik

5条回答
  •  天涯浪人
    2021-02-07 02:24

    I think the difference has nothing to do with tail-call optimization, or optimization at all. The reason I think that is that the optimization can, at it's best, only achieve something that is like your iterative Java version.

    The real reason is, IMHO, that Java BigIntegers are slow compared with Haskell's.

    To establish this, I propose 2 experiments:

    1. Use the same algorithms, but use long. (The results will be some garbage for higher numbers, but the computations will be done nevertheless.) Here, the Java version should be on par with Haskell.

    2. Use a faster big integer library in the java version. The performance should improve accordingly. There are wrappers for GMP out there, as well as improvements to the java big integers like here. The manyfold performance imporvements possible for multiplication of large numbers are telling.

提交回复
热议问题