send(:method_name)和method(:method_name).call之间有区别吗?

时间:2014-12-31 09:23:06

标签: ruby

红宝石中sendmethod().call之间是否存在差异?

1.send(:to_f)
=> 1.0
1.method(:to_f).call
=> 1.0

但对我来说两者似乎都是一样的。

1 个答案:

答案 0 :(得分:10)

从您的角度来看,他们做同样的事情。但method的版本速度要慢得多(因为它会做更多的东西"在幕后"就像创建一个方法对象一样)

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report('plain send') do |times|
    1.send(:to_f)
  end
  x.report('method with call') do |times|
    1.method(:to_f).call
  end

  x.compare!
end

结果

Calculating -------------------------------------
          plain send   142.776k i/100ms
    method with call    73.266k i/100ms
-------------------------------------------------
          plain send    143.863B (±17.0%) i/s -    178.678B
    method with call     73.358B (±18.1%) i/s -    106.276B

Comparison:
          plain send: 143862537517.5 i/s
    method with call: 73358071888.5 i/s - 1.96x slower