Skip to content

Instantly share code, notes, and snippets.

@kalmanh
Created April 25, 2013 22:33
Show Gist options
  • Save kalmanh/5463788 to your computer and use it in GitHub Desktop.
Save kalmanh/5463788 to your computer and use it in GitHub Desktop.
Comparing Fibonacci memoization using class variable vs. class instance variable
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)
@kalmanh
Copy link
Author

kalmanh commented Apr 25, 2013

Class variable code taken from Eno Compton blog... Interesting...

http://www.commandercoriander.net/blog/2013/04/10/metaprogramming-fibonacci/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment