Benchmarking Recursion Using Factorial Function

def fact(n)
  (1..n).to_a.inject(1){|f,n| f*n}
end

def recursive_fact(n)
  return n==1 ? n : n * recursive_fact(n-1)
end

require ‘benchmark’

Benchmark.bm do |b|
  b.report(“inject”){1000.times{fact(100)}}
  b.report(“recursive”){1000.times{recursive_fact(100)}}
end


Posted

in

,

by

Tags: