środa, 18 sierpnia 2010

String#constantize . Can it be faster ?


BigNumber = 100_000
Constants = ["Rails", "ActiveSupport::Autoload", "ActiveSupport::Dependencies::LoadingModule"]

def test
BigNumber.times do
Constants.each do |c|
yield c
end
end
end

Benchmark.bmbm do |x|

x.report("custom ok") do
test do |const|
const = '::' << const unless const.starts_with?("::")
eval(const)
end
end

x.report("custom wrong") do
test do |const|
eval(const)
end
end

x.report("active support implementation") do
test do |const|
names = const.split('::')
names.shift if names.empty? || names.first.empty?

constant = Object
names.each do |name|
constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name)
end
constant
end
end
end




And the results for Ruby 1.9.2 are:


Rehearsal --------------------------------------------------
custom ok 5.220000 0.020000 5.240000 ( 5.412122)

custom wrong 4.550000 0.020000 4.570000 ( 4.716120)

active support 1.560000 0.000000 1.560000 ( 1.597956)
implementation
---------------------------------------- total: 11.370000sec

user system total real
custom ok 5.180000 0.000000 5.180000 ( 5.273098)

custom wrong 4.450000 0.030000 4.480000 ( 4.547156)

active support 1.570000 0.000000 1.570000 ( 1.576236)
implementation