What is faster on later invocation:
def first_method?() second_method?() end
or
alias_method :first method, :second_method
and if possible why?
(NOTE: I don't ask what is nicer / better etc. -> only raw speed and why it is faster is interesting here)
At least in Ruby 1.8.6, aliasing seems to be faster:
#!/usr/local/bin/ruby
require 'benchmark'
$global_bool = true
class Object
def first_method?
$global_bool
end
def second_method?
first_method?
end
alias_method :third_method?, :first_method?
end
Benchmark.bm(7) do |x|
x.report("first:") { 1000000.times { first_method? }}
x.report("second:") { 1000000.times { second_method? }}
x.report("third:") { 1000000.times { third_method? }}
end
results in :
$ ./test.rb
user system total real
first: 0.281000 0.000000 0.281000 ( 0.282000)
second: 0.469000 0.000000 0.469000 ( 0.468000)
third: 0.281000 0.000000 0.281000 ( 0.282000)
Obviously, you have one method call less (look-up receiver ...). So it seems natural for it to be faster.
a quick look at the source code, will show you the trick:
http://www.ruby-doc.org/core/classes/Module.src/M000447.html
alias_method is written in C. moreover, defining a method in ruby that calls another method, will result in 2 method lookups and calls.
so, alias_method should be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With