开发者

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_meth开发者_开发百科od :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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜