3.times { print "Ruby! " }
Maybe why you don’t see recursion used much in Ruby

You’re also highly likely to hit the stack limit in Ruby with recursion, and I don’t think there’s a simple way to alter the stack size.

jrwest:

I may be wrong but if my CS classes haven’t left me yet I believe you will find this in all programming languages. Iterative algorithms always run faster than recursive ones.

stevegraham:

I’ve become interested in recursion and functional programming lately in the interests of sharpening one’s saw, and was interested to see how recursion performed in Ruby.

Consider the following code:

require 'benchmark'

def recursive_factorial(n)
  n == 0 ? 1 : n * recursive_factorial(n-1)
end

def iterative_factorial(n)
  (1..n).reduce :*
end

Benchmark.bmbm do |x|
  x.report("recursive:") { 10000.times { recursive_factorial 1000 } }
  x.report("iterative:") { 10000.times { iterative_factorial 1000 } }
end

Yields the following benchmark:

Rehearsal ----------------------------------------------
recursive:  53.670000   2.560000  56.230000 ( 57.035829)
iterative:  32.540000   2.330000  34.870000 ( 35.629017)
------------------------------------ total: 91.100000sec

                 user     system      total        real
recursive:  77.420000   3.740000  81.160000 ( 88.844745)
iterative:  41.870000   3.200000  45.070000 ( 64.231568)

Considerable difference in performance. The iterative method looks a lot more simple and elegant too in my opinion.

blog comments powered by Disqus