Stefan Lang
3/12/2008 11:12:00 AM
2008/3/12, Frantisek Psotka <frantisek.psotka@matfyz.cz>:
> Hi.
>
> Iam not very deep in ruby. Please answer:
>
> 1) is the attr (method) slower than instance_variable_get/set ?
They serve different purposes. attr defines accessor methods
and the other allows access to instance variables via computed
variable names. So I'm not exactly sure what the purpose of the
speed comparison is.
Well, a let's benchmark anyway:
> require "benchmark"
> class Foo
> attr :a, true
> def initialize
> @a = :a
> end
> end
=> nil
> f = Foo.new
=> #<Foo:0xb7adeb18 @a=:a>
> Benchmark.bm { |x| x.report { 1_000_000.times { f.a } } }
user system total real
0.560000 0.090000 0.650000 ( 0.656214)
=> true
> Benchmark.bm { |x| x.report { 1_000_000.times {
f.instance_variable_get :@a } } }
user system total real
0.590000 0.100000 0.690000 ( 0.705093)
=> true
> Benchmark.bm { |x| x.report { 1_000_000.times { f.a = 1 } } }
user system total real
0.590000 0.090000 0.680000 ( 0.698388)
=> true
> Benchmark.bm { |x| x.report { 1_000_000.times {
f.instance_variable_set :@a, 1 } } }
user system total real
0.650000 0.090000 0.740000 ( 0.759085)
=> true
Conclusion: The differences are noise.
> 2) How can I define [] for instance_var_get/set (like in struct) ?
class Foo
def [](attr_name)
instance_variable_get :"@#{attr_name}"
end
def []=(attr_name, value)
instance_variable_set :"@#{attr_name}", value
end
end
Though using [] and []= will definitely be slower than using
classic accessor methods because we have to construct
the instance variable name for every access.
> 3) Is there a way to undefine @variable. I assign nil to them, but in
> to_yaml output they are still there (even if empty). Is there way to
> undefine them?
"ri instance_variable" reveals Object#remove_instance_variable.
Stefan