Hacker News new | ask | show | jobs
by ricardobeat 5370 days ago
I'm getting 0.020s tops for that fibonacci code on node (time curl http://localhost/), even going up to `1.1210238130165696e+167` (800th number). OSX Lion on a C2d 2.3ghz.

Python 2.7.1 took 1m25.259s (no server).

Am I doing something wrong? Or is there some incredibly optimized code path for OSX?

edit: even weirder, `time node fibonacci.js` without a server takes 0.090s.

1 comments

Sure you're calling fibonacci(40) and not just defining the function?
Yes. Turns out that the recursion overhead in python is huge, it can get down to <100ms too with a non-recursive function.
I have no idea whether that is true and I'm not arguing with it.

Why are you writing web request handlers containing heavily recursive code, and why do you seem to think that indicates anything meaningful about Python?

Please tell me you are not also using SimpleHTTPServer to try to prove points about Python's performance (like http://joshuakehn.com/2011/10/3/Diagnosis-No-Cancer.html and http://blog.brianbeck.com/post/node-js-cures-cancer)

I wasn't. I was just curious about the huge difference in performance. These numbers are from printing to console, no servers.

    def fibonacci(n):
        t = [0, 1]
        for i in xrange(n):
            t.append(t[-1] + t[-2])
        return t[-2]
    
    print fibonacci(800)
Technically the above is a dynamic programming algorithm, in that you are avoiding the recomputation of fib(1..n-1) in each step. That is equivalent to recursion+memoization, which would perform roughly similar to the above. So it is not that "recursion" is so dramatically slower than "iteration" in general, it's just that for these kinds of computations, recursion should be memoized.