Alle marted12 giugno 2007, Daniel Liebig ha scritto: > Do you know if instance_variable_set() behaves different or is more > performant in any way than eval()? > Or is it just better readable code? Here's a small benchmark to test performances: require 'benchmark' $h = {} n.times{|i| $h["@v_#{i}"] = i} class C def initialize $h.each_pair{|k, v| instance_variable_set(k,v)} end end class D def initialize $h.each_pair{|k, v| eval "@#{k} = '#{v}'"} end end Benchmark.bm('instance_variable_set:'.size) do |x| x.report('instance_variable_set:'){C.new} x.report('eval:'){D.new} end The results are: - n = 500: user system total real instance_variable_set: 0.010000 0.000000 0.010000 ( 0.015151) eval: 0.030000 0.010000 0.040000 ( 0.032303) - n = 1000: user system total real instance_variable_set: 0.020000 0.000000 0.020000 ( 0.027947) eval: 0.060000 0.000000 0.060000 ( 0.072785) It's clear that instance_variable_set is more performant. I'm not sure, but I think this happens because with eval, the interpreter also needs to parse the string you pass to eval. Stefano