-3

I have a question about the performance of IP and FP. Let's say I have a function to compute nth Fibonacci number.

In imperative programming I have a choice to computing the nth Fibonacci number using iterative way, recursion, or dynamic programming. Of course iterative way and dynamic programming will perform better compared to recursion asymptotically.

In functional programming, assume there is no state involved, then I can only do it in recursion way.

In this case, doesn't that mean functional programming will always perform as equal or slower compared to imperative programming in terms of efficiency (asymptotically)?

How does real world functional programming deal with this issue?

David Gao
  • 906
  • 4
  • 12
  • 23
  • You're assuming a lot about both imperative and functional programming. Several functional languages allow impure behavior for exactly those cases where performance is an overriding concern. – Onorio Catenacci Sep 12 '12 at 01:19

1 Answers1

7

There is no one recursive way to implement the Fibonacci numbers. You can easily write a recursive function that calculates the nth Fibonacci numbers in O(n) time - it would work the same way as the iterative version (i.e. it'd keep track of the last two numbers you've calculated), but using tail recursion instead of an imperative loop. Since many functional languages require implementations to perform tail call optimization, there won't even be constant overhead compared to the iterative version.

And of course there are even ways to calculate the nth Fibonacci number in sublinear time (using the closed form or matrix multiplication), which work just as well in functional languages as in imperative languages.

Regarding dynamic programming: It is perfectly possible to do dynamic programming in functional languages. Since dynamic programming algorithms don't change a field of the array once it has been written for the first time, there is really no contradiction to functional programming here. All you need is to be able to access the already constructed parts of the array while the array is being constructed. Lazy arrays as they exist in Haskell work well for this.

sepp2k
  • 363,768
  • 54
  • 674
  • 675