What works faster in Ruby: defining an alias method or using alias_method?

What happens faster on a subsequent call:

def first_method?() second_method?() end 

or

 alias_method :first method, :second_method 

and, if possible, why?

(NOTE: I do not ask what is better / better, etc. → only interesting speed here and why it is faster)

+8
performance ruby aliasing
source share
2 answers

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. In addition, defining a method in ruby ​​that calls another method will result in a search and calls from two methods.

therefore alias_method should be faster.

+7
source share

At least in Ruby 1.8.6, anti-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 

leads to:

 $ ./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 less method (look-up receiver ...). Therefore, for him it seems natural faster.

+13
source share

All Articles