Skip to content

Instantly share code, notes, and snippets.

@cosmo0920
Created December 9, 2016 07:19
Show Gist options
  • Save cosmo0920/07bb380d494cd14ced20a111d7f98512 to your computer and use it in GitHub Desktop.
Save cosmo0920/07bb380d494cd14ced20a111d7f98512 to your computer and use it in GitHub Desktop.
require "benchmark"
src = "[[tag, time, record['code'].to_i]]"
map = "#{src}"
tag = "foo"
time = 12345
record = {
"code" => "400"
}
class A
end
a = A.new
a.singleton_class.module_eval(<<-CODE)
def map_func(tag, time, record)
#{map}
end
CODE
a.singleton_class.class_eval <<-EORUBY, __FILE__, __LINE__ + 1
def map_class_eval(tag, time, record)
#{map}
end
EORUBY
p a.map_class_eval(tag, time, record)
p a.map_func(tag, time, record)
p eval(src)
N = 10000
Benchmark.bmbm do |x|
x.report("class_eval") do
N.times do
a.map_class_eval(tag, time, record)
end
end
x.report("module_eval") do
N.times do
a.map_func(tag, time, record)
end
end
x.report("eval") do
N.times do
eval(src)
end
end
end
$ ruby bench.rb
[["foo", 12345, 400]]
[["foo", 12345, 400]]
[["foo", 12345, 400]]
Rehearsal -----------------------------------------------
class_eval 0.010000 0.000000 0.010000 ( 0.005329)
module_eval 0.000000 0.000000 0.000000 ( 0.003275)
eval 0.120000 0.000000 0.120000 ( 0.120336)
-------------------------------------- total: 0.130000sec
user system total real
class_eval 0.000000 0.000000 0.000000 ( 0.003177)
module_eval 0.010000 0.000000 0.010000 ( 0.003216)
eval 0.110000 0.000000 0.110000 ( 0.118929)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment