Created
March 20, 2015 18:39
-
-
Save tdg5/8b77b443616446b39f8b to your computer and use it in GitHub Desktop.
4 kinds of factorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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