正如您在下面的示例中所看到的,javascript / node比haskell快得多 但是haskell是基于C编译的。在这个例子中,你看到C是最快的。为什么haskell比较慢?
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
1346269个
真实0m0,045s
用户0m0,040s
sys 0m0,004s
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
main = print (fib 30)
$ ghc -o fibh fib.hs
$ time ./fibh
1346269个
真实0m0,178s
用户0m0,168s
sys 0m0,000s
#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
$ time ./fibc
cfib:1346269
真正的0m0,023s
用户0m0,020s
sys 0m0,000s
$ ghc -O2 -o fibh fib.hs
$ time ./fibh
1346269
real 0m0,166s
user 0m0,160s
sys 0m0,004s
答案 0 :(得分:10)
这只是因为GMP Integer
和机器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