Created
October 3, 2016 21:15
-
-
Save avinashbot/60d5ac0b24e6fcac3fc8de4d18c65589 to your computer and use it in GitHub Desktop.
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 MethodMissing | |
attr_reader :attributes | |
def initialize(attributes) | |
@attributes = attributes | |
end | |
def method_missing(prop, *args, &block) | |
return super unless @attributes.include?(prop) | |
@attributes[prop] | |
end | |
end | |
class MemoizedMethodMissing | |
attr_reader :attributes | |
def initialize(attributes) | |
@attributes = attributes | |
end | |
def method_missing(prop, *args, &block) | |
return super unless @attributes.include?(prop) | |
define_singleton_method(prop) { @attributes[prop] } | |
@attributes[prop] | |
end | |
end | |
class DefineMethod | |
attr_reader :attributes | |
def initialize(attributes) | |
@attributes = attributes | |
end | |
[:one, :two].each { |m| define_method(m) { @attributes[m] } } | |
end | |
Benchmark.bm do |x| | |
mm = MethodMissing.new(one: 1, two: '2') | |
mmm = MemoizedMethodMissing.new(one: 1, two: '2') | |
dm = DefineMethod.new(one: 1, two: '2') | |
x.report do | |
500_000.times { mm.one; mm.two } | |
end | |
x.report do | |
500_000.times { mmm.one; mmm.two } | |
end | |
x.report do | |
500_000.times { dm.one; dm.two } | |
end | |
end | |
# user system total real | |
# 0.200000 0.000000 0.200000 ( 0.208867) | |
# 0.110000 0.000000 0.110000 ( 0.114226) | |
# 0.100000 0.000000 0.100000 ( 0.115317) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment