Skip to content

Instantly share code, notes, and snippets.

@Narnach
Created December 17, 2008 14:49
Show Gist options
  • Save Narnach/37074 to your computer and use it in GitHub Desktop.
Save Narnach/37074 to your computer and use it in GitHub Desktop.
Benchmark to show methods defined using define_method are _slow_
#!/usr/bin/env ruby
#
# Methods defined using Ruby's define_method are slower to invoke than normally defined (eval-ed) methods.
# Using ruby2ruby we can re-define them and get a speedup.
require 'rubygems'
require 'ruby2ruby'
require 'benchmark'
module Bench
def self.optimize(obj)
code = Ruby2Ruby.translate(obj)
# puts code
eval code
end
class One
def self.add_slow_method(name,&block)
define_method(name, &block)
end
def three
3
end
end
end
Bench::One.add_slow_method('one') do
1
end
Bench::One.add_slow_method('two') do
2
end
n = 100_000
Benchmark.bm do |x|
one = Bench::One.new
x.report('define_method :one') do
n.times {one.one}
end
x.report('define_method :two') do
n.times {one.two}
end
x.report('def three') do
n.times {one.three}
end
Bench.optimize(Bench::One)
x.report('define_method :one (after ruby2ruby re-define)') do
n.times {one.one}
end
x.report('def three (after ruby2ruby re-define)') do
n.times {one.three}
end
end
The output on my macbook:
user system total real
define_method :one 0.130000 0.010000 0.140000 ( 0.135645)
define_method :two 0.130000 0.000000 0.130000 ( 0.137308)
def three 0.040000 0.000000 0.040000 ( 0.044475)
define_method :one (after ruby2ruby re-define) 0.050000 0.000000 0.050000 ( 0.046069)
def three (after ruby2ruby re-define) 0.040000 0.000000 0.040000 ( 0.046385)
Before re-defining, define_method methods are about 3 times slower to invoke. After re-defining the speed is similar.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment