As we've seen in this section, there are several ways to invoke an
arbitrary method of some object:
Object#send
,
Method#call
, and the various flavors of
eval
.
You may prefer to use any one of these techniques depending on your
needs, but be aware that
eval
is significantly slower than the
others (or, for optimistic readers,
send
and
call
are
significantly faster than
eval
).
require "benchmark" # from the Ruby Application Archive
include Benchmark
test = "Stormy Weather"
m = test.method(:length)
n = 100000
bm(12) {|x|
x.report("call") { n.times { m.call } }
x.report("send") { n.times { test.send(:length) } }
x.report("eval") { n.times { eval "test.length" } }
}
|
produces:
user system total real
call 0.220000 0.000000 0.220000 ( 0.214065)
send 0.210000 0.000000 0.210000 ( 0.217070)
eval 2.540000 0.000000 2.540000 ( 2.518311)
|