Skip to content

Instantly share code, notes, and snippets.

@tdg5
Created March 20, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdg5/8b77b443616446b39f8b to your computer and use it in GitHub Desktop.
Save tdg5/8b77b443616446b39f8b to your computer and use it in GitHub Desktop.
4 kinds of factorial
require "benchmark/ips"
def recursive_factorial(n)
n < 2 ? 1 : n * recursive_factorial(n - 1)
end
def tail_recursive_factorial(n, accumulator = 1)
n < 2 ? accumulator : tail_recursive_factorial(n - 1, n * accumulator)
end
code = <<-CODE
def tco_factorial(n, accumulator = 1)
n < 2 ? accumulator : tco_factorial(n - 1, n * accumulator)
end
CODE
RubyVM::InstructionSequence.new(code, nil, nil, nil, {
tailcall_optimization: true,
trace_instruction: false,
}).eval
def loopy_factorial(n)
return 1 if n < 2
accumulator = 1
while n > 1
accumulator *= n
n -= 1
end
accumulator
end
i = 15
Benchmark.ips do |bm|
bm.report("recursive_factorial") do
recursive_factorial(i)
end
bm.report("tail_recursive_factorial") do
tail_recursive_factorial(i)
end
bm.report("tco_factorial") do
tco_factorial(i)
end
bm.report("loopy_factorial") do
loopy_factorial(i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment