Why is Haskell so slow compared to C for Fibonacci sequence?

前端 未结 2 1381
囚心锁ツ
囚心锁ツ 2021-01-29 06:44

I am just beginner in Haskell. And I writing a code to display the N numbers in the Fibonacci sequence. Here is my code in Haskell,

fib_seq 1 = 1:[]
fib_seq 2 =          


        
相关标签:
2条回答
  • 2021-01-29 07:26

    Guess what happens if "fib_seq (n-1)" is evaluated twice on each recursion. And then try this:

    fib_seq 1 = 1:[]
    fib_seq 2 = 1:1:[]
    fib_seq n = sum(take 2 f):f
                where f = fib_seq (n-1)
    
    0 讨论(0)
  • 2021-01-29 07:37

    The following program, compiled with ghc -O2 test.hs, is +/-2% the speed of the C code you posted, compiled with gcc -O2 test.c.

    fib_seq :: Int -> Int
    fib_seq 1 = 1
    fib_seq 2 = 1
    fib_seq n = fib_seq (n-1) + fib_seq (n-2)
    
    main = mapM_ (print . fib_seq) [40,39..1]
    

    Some comments:

    1. Unlike you, I implemented the exact same logic. I doubt this is the real difference, though; see the remaining comments for much more likely causes.
    2. I specified the same types as C uses for the arithmetic. You didn't, which is likely to run into two problems: using Integer instead of Int for largenum arithmetic, and having a class-polymorphic type instead of a monomorphic one adding overhead on every function call.
    3. I compiled. ghci is built to be interactive as quickly as possible, not to produce quick code.
    4. I don't have the right version of llvm installed at the moment, but it will often crunch through heavily-numeric code like this much better than ghc's own codegen. I wouldn't be too surprised if it ended up being faster than gcc.

    Of course using one of the many well-known better algorithms for fibonacci is going to trump all this nonsense.

    0 讨论(0)
提交回复
热议问题