Created
April 25, 2013 22:33
-
-
Save kalmanh/5463788 to your computer and use it in GitHub Desktop.
Comparing Fibonacci memoization using class variable vs. class instance variable
This file contains hidden or 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' | |
class Fibonacci_Class_Data_Variable | |
@@memo = { 0 => 0, 1 => 1 } | |
def self.fib_rec(n) | |
@@memo[n] ||= fib_rec(n - 1) + fib_rec(n - 2) | |
end | |
end | |
class Fibonacci_Class_Instance_Variable | |
@memo = { 0 => 0, 1 => 1 } | |
def self.fib_rec(n) | |
@memo[n] ||= fib_rec(n - 1) + fib_rec(n - 2) | |
end | |
end | |
test_for = 7250 | |
Benchmark.bmbm do |x| | |
x.report("Class (Data) Variable") { Fibonacci_Class_Data_Variable.fib_rec(test_for) } | |
x.report("Class Instance Variable") { Fibonacci_Class_Instance_Variable.fib_rec(test_for) } | |
end | |
# Rehearsal ----------------------------------------------------------- | |
# Class (Data) Variable 0.000000 0.000000 0.000000 ( 0.013001) | |
# Class Instance Variable 0.015000 0.000000 0.015000 ( 0.011001) | |
# -------------------------------------------------- total: 0.015000sec | |
# | |
# user system total real | |
# Class (Data) Variable 0.000000 0.000000 0.000000 ( 0.000000) | |
# Class Instance Variable 0.000000 0.000000 0.000000 ( 0.000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Class variable code taken from Eno Compton blog... Interesting...
http://www.commandercoriander.net/blog/2013/04/10/metaprogramming-fibonacci/