Skip to content

Instantly share code, notes, and snippets.

@jordanfowler
Created August 24, 2009 23:19
Show Gist options
  • Save jordanfowler/174301 to your computer and use it in GitHub Desktop.
Save jordanfowler/174301 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'ostruct'
class LocalStruct < OpenStruct
def run_proc(&block)
instance_eval(&block) if block_given?
end
end
class LocalStruct2
def initialize(attributes={})
if attributes.respond_to?(:each_pair)
attributes.each_pair do |name, value|
add_method(name){ value }
end
end
end
def add_method(name, &block)
self.class.class_eval{
define_method(name, &block)
}
end
def run_proc(&block)
instance_eval(&block) if block_given?
end
end
environment = LocalStruct.new :name => 'Jordan Fowler'
environment.age = 24
environment.run_proc { puts "#{name} is #{age} years old" }
env2 = LocalStruct2.new :name => 'Jordan Fowler'
env2.add_method('age'){ 24 }
env2.run_proc { puts "#{name} is #{age} years old" }
n = 100_000
puts "accessing the var"
Benchmark.bm do |x|
x.report("method_missing:") do
n.times do
environment.run_proc { "#{name} is #{age} years old" } # => "Jordan Fowler"
end
end
x.report("define_method:") do
n.times do
env2.run_proc { "#{name} is #{age} years old" }
end
end
end
Jordan Fowler is 24 years old
Jordan Fowler is 24 years old
accessing the var
user system total real
method_missing: 0.690000 0.010000 0.700000 ( 0.772148)
define_method: 0.660000 0.010000 0.670000 ( 0.768362)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment