简体   繁体   English

为什么在javascript中斐波那契的计算比haskell更快?

[英]Why is the calculation of fibonacci faster in javascript than haskell?

As you can see in the examples below, javascript/node is much faster then haskell. 如您在以下示例中看到的,javascript / node比haskell快得多。
But haskell is compiled and based on C. In the example, you see that C is the fastest. 但是haskell是基于C编译的。在示例中,您看到C是最快的。 How comes that haskell is so slow in comparison? 相比之下,haskell为何这么慢?

JS executed by node: JS由节点执行:

function fib(n) {
    if ( n==0 || n==1 )
        return 1;

    return fib(n-2)+fib(n-1);
}
console.log(fib(30));

$ time node fib.js $时间节点fib.js
1346269 1346269
real 0m0,045s 实际0m0,045s
user 0m0,040s 用户0m0,040s
sys 0m0,004s sys 0分0,004秒

haskell: haskell:

fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

main = print (fib 30)

$ ghc -o fibh fib.hs $ ghc -o fibh fib.hs
$ time ./fibh $ time ./fibh
1346269 1346269
real 0m0,178s 真实0m0,178s
user 0m0,168s 用户0m0,168s
sys 0m0,000s sys 0m0,000s

c: C:

#include <stdio.h>

int fib(int n) {
    if (n == 0 || n == 1) 
        return 1;

    return fib(n-1)+fib(n-2);
}

int main() {
    int f = fib(30);
    printf("cfib: %i\n", f);
}

$ gcc fib.c -o fibc $ gcc fib.c -o fibc
$ time ./fibc $ time ./fibc
cfib: 1346269 cfib:1346269
real 0m0,023s 真正的0m0,023s
user 0m0,020s 用户0m0,020s
sys 0m0,000s sys 0m0,000s

EDIT1: 编辑1:

haskell with -O2 like suggested 建议使用带有-O2的haskell

$ ghc -O2 -o fibh fib.hs
$ time ./fibh
1346269
real 0m0,166s
user 0m0,160s
sys 0m0,004s

It is just because of the difference between GMP Integer s and machine Int s: 仅仅是因为GMP Integer和machine Int之间的差异:

% cat fib.hs
fib :: Int -> Int -- N.B. default is `Integer`
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

main = print (fib 30)


% ghc -O2 fib.hs && time ./fib
1346269
./fib  0.01s user 0.00s system 87% cpu 0.013 total

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM