Search code examples
performancefunctional-programmingfactorial

Why is computing a factorial faster/efficient in functional programming?


Here's a claim made in one of the answers at: https://softwareengineering.stackexchange.com/a/136146/18748

Try your hand at a Functional language or two. Try implementing factorial in Erlang using recursion and watch your jaw hit the floor when 20000! returns in 5 seconds (no stack overflow in site)

Why would it be faster/more efficient than using recursion/iteration in Java/C/C++/Python (any)? What is the underlying mathematical/theoretical concept that makes this happen? Unfortunately, I wasn't ever exposed to functional programming in my undergrad (started with 'C') so I may just lack knowing the 'why'.


Solution

  • A recursive solution would probably be slower and clunkier in Java or C++, but we don't do things that way in Java and C++, so. :)

    As for why, functional languages invariably make very heavy usage of recursion (as by default they either have to jump through hoops, or simply aren't allowed, to modify variables, which on its own makes most forms of iteration ineffective or outright impossible). So they effectively have to optimize the hell out of it in order to be competitive.

    Almost all of them implement an optimization called "tail call elimination", which uses the current call's stack space for the next call and turns a "call" into a "jump". That little change basically turns recursion into iteration, but don't remind the FPers of that. When it comes to iteration in a procedural language and recursion in a functional one, the two would prove about equal performancewise. (If either one's still faster, though, it'd be iteration.)

    The rest is libraries and number types and such. Decent math code ==> decent math performance. There's nothing keeping procedural or OO languages from optimizing similarly, other than that most people don't care that much. Functional programmers, on the other hand, love to navel gaze about how easily they can calculate Fibonacci sequences and 20000! and other numbers that most of us will never use anyway.