Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What runs faster in Ruby: defining the alias method or using alias_method?

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)

like image 757
Szymon Jeż Avatar asked Sep 02 '11 10:09

Szymon Jeż


2 Answers

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.

like image 63
undur_gongor Avatar answered Nov 13 '22 18:11

undur_gongor


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.

like image 37
Andrea Pavoni Avatar answered Nov 13 '22 18:11

Andrea Pavoni