public
Created

Benchmark on using instance_variable_set v.s. instance_eval

  • Download Gist
bench.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
require 'benchmark'
 
class Foo
def bar
true
end
end
 
n = 1_000_000
Benchmark.bm(30) do | b |
b.report "instance_variable_set" do
n.times do
instance = Foo.new
instance.instance_variable_set(:@baz, Hash.new)
end
end
 
b.report "instance_eval" do
n.times do
instance = Foo.new
instance.instance_eval do
@baz = Hash.new
end
end
end
end
 
 
# user system total real
# instance_variable_set 0.720000 0.000000 0.720000 ( 0.715357)
# instance_eval 5.280000 0.000000 5.280000 ( 5.284949)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.