Kalman Noel
9/23/2006 1:52:00 PM
Marcin MielżyÅ?ski:
> dblack@wobblini.net wrote:
>> class Object
>> def const_get_recursive(const)
>> const.split("::").inject(Object) {|c1,c2| c1.const_get(c2)}
>> end
>> end
>
> I know that eval is not save but it appears that it is much faster than
> inject version
>
> class A
> class B
> C = "foo"
> end
> end
You may speed your method up a little by avoiding blocks with multiple
arguments, as following. Still eval is fastest, though, of course, nobody will
recommend it.
class Object
def const_get_eaching(const)
c = Object
const.split('::').each { |x| c = c.const_get x }
c
end
end
n=10000
Benchmark.bm do |x|
x.report("eval") { n.times{ eval("A::B::C") }}
x.report("inject") { n.times{ Object.const_get_recursive("A::B::C") }}
x.report("each") { n.times{ Object.const_get_eaching("A::B::C") }}
end
# Results:
user system total real
eval 0.100000 0.000000 0.100000 ( 0.101864)
inject 0.210000 0.040000 0.250000 ( 0.258335)
each 0.160000 0.030000 0.190000 ( 0.184249)
Kalman