Created
May 31, 2012 20:18
-
-
Save nyarly/2845937 to your computer and use it in GitHub Desktop.
Dynamic method def: eval strings vs define_method with a block
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
Adding 1 10x10 times: 100 | |
Adding 1 10x10 times: 100 | |
user system total real | |
evald 15.760000 0.000000 15.760000 ( 15.772606) | |
block 15.920000 0.000000 15.920000 ( 15.926385) | |
user system total real | |
eval_string 10.070000 0.110000 10.180000 ( 10.184233) | |
define_with_block 1.120000 0.020000 1.140000 ( 1.143636) | |
Comment: running the methods is very close. Defining the methods: order of magnitude slower to eval strings. |
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 DynamicMethods | |
def self.eval_string(name, count) | |
class_eval <<-EOM | |
def #{name}(count_prime) | |
x = 0 | |
count_prime.times do | |
#{count}.times do | |
x += 1 | |
end | |
end | |
return x | |
end | |
EOM | |
end | |
def self.define_with_block(name, count) | |
define_method name do |count_prime| | |
x = 0 | |
count_prime.times do | |
count.times do | |
x += 1 | |
end | |
end | |
return x | |
end | |
end | |
end | |
# Setup: | |
DynamicMethods.eval_string(:evald_10, 10) | |
DynamicMethods.define_with_block(:block_10, 10) | |
dm = DynamicMethods.new | |
puts "Adding 1 10x10 times: #{dm.evald_10(10)}" #=> 100 | |
puts "Adding 1 10x10 times: #{dm.block_10(10)}" #=> 100 | |
repeat_count = 10000 | |
Benchmark.bm do |bm| | |
bm.report("evald") { repeat_count.times { dm.evald_10(10) } } | |
bm.report("block") { repeat_count.times { dm.block_10(10) } } | |
end | |
setup_count = 100000 | |
Benchmark.bm do |bm| | |
bm.report("eval_string") { setup_count.times {|idx| DynamicMethods.eval_string("eval_bm_#{idx}", idx) } } | |
bm.report("define_with_block") { setup_count.times {|idx| DynamicMethods.define_with_block("defwblk_#{idx}", idx) } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment