-
-
Save 0xqd/3482807 to your computer and use it in GitHub Desktop.
Ruby Self-Modification Example - Memoize
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' | |
class Fib | |
def fib(n) | |
return n if n < 2 | |
return fib(n-1) + fib(n-2) | |
end | |
end | |
def memoize(className, methodName) | |
className.class_eval do | |
alias_method("original_memoize_#{methodName}", methodName) | |
define_method(methodName) do |*args| | |
hash = instance_variable_get("@memoize_#{methodName}_hash") | |
if hash.nil? | |
hash = Hash.new | |
instance_variable_set("@memoize_#{methodName}_hash", hash) | |
end | |
return hash[args] if hash.has_key?(args) | |
res = self.send("original_memoize_#{methodName}", *args) | |
hash[args] = res | |
return res | |
end | |
end | |
end | |
if ARGV.length != 1 | |
puts "Usage: meta.rb <number>" | |
exit | |
end | |
num = ARGV[0].to_i | |
puts "Running Fib with #{num}" | |
res1 = res2 = 0 | |
a = Fib.new | |
puts "Without Memoization:" | |
puts Benchmark.measure { | |
res1 = a.fib(num) | |
} | |
memoize(Fib, :fib) | |
a = Fib.new | |
puts "With Memoization:" | |
puts Benchmark.measure { | |
res2 = a.fib(num) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment