Pit Capitain
12/27/2006 3:44:00 PM
Daniel Berger schrieb:
> I came across a technique for aliasing methods that I have never seen
> before [1] and was just too good to pass up. (...)
Dan, this is a nice technique indeed (not new, but still nice), but it
comes with a performance penalty:
class HashUsingAlias < Hash
alias :old_hset :[]=
def []=(key, value)
self.old_hset(key, value)
end
end
class HashUsingBind < Hash
hset = self.instance_method(:[]=)
define_method(:[]=) do |key, value|
hset.bind(self).call(key, value)
end
end
require "benchmark"
def bm_report bm, title, hash_class
hash = hash_class.new
bm.report title do
100_000.times do
hash[ 1 ] = 1
end
end
end
Benchmark.bmbm do |bm|
bm_report bm, "original", Hash
bm_report bm, "alias", HashUsingAlias
bm_report bm, "bind", HashUsingBind
end
On my system, I get the following results:
user system total real
original 0.062000 0.000000 0.062000 ( 0.062000)
alias 0.141000 0.000000 0.141000 ( 0.140000)
bind 0.656000 0.000000 0.656000 ( 0.657000)
Regards,
Pit