Skip to content

Instantly share code, notes, and snippets.

@zmack
Created April 27, 2012 15:21
Show Gist options
  • Save zmack/2510110 to your computer and use it in GitHub Desktop.
Save zmack/2510110 to your computer and use it in GitHub Desktop.
require 'forwardable'
require 'benchmark'
class Fakenum
extend Forwardable
attr_reader :thing
def initialize
@thing = 1
end
def thing_odd?
@thing.odd?
end
def method_missing(method, *args)
if method == :foobar
@thing.odd?
elsif method == :foobaz
self.class.class_eval(<<-EOD, __FILE__, __LINE__)
def foobaz
@thing.odd?
end
EOD
foobaz
end
end
def_delegators :@thing, *(Fixnum.instance_methods - self.instance_methods)
end
fn = Fakenum.new
p fn.odd?
p fn.foobar
p fn.foobaz
p fn.thing_odd?
p fn.thing.odd?
Benchmark.bm do |r|
r.report('Foo') do
1_000_000.times { fn.odd? }
end
r.report('Bar') do
1_000_000.times { fn.foobar }
end
r.report('Baz') do
1_000_000.times { fn.foobaz }
end
r.report('Fle') do
1_000_000.times { fn.thing_odd? }
end
r.report('Ele') do
1_000_000.times { fn.thing.odd? }
end
end
true
true
true
true
true
user system total real
Foo 0.990000 0.000000 0.990000 ( 0.989358)
Bar 0.720000 0.000000 0.720000 ( 0.713166)
Baz 0.320000 0.000000 0.320000 ( 0.323896)
Fle 0.330000 0.000000 0.330000 ( 0.326319)
Ele 0.220000 0.000000 0.220000 ( 0.228836)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment