Mon22Mar

  1. Maybe why you don’t see recursion used much in Ruby

    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.

    EDIT: jrwest - obviously, but is the difference always as stark?