[英]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为何这么慢?
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秒
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
#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
$ 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.