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

iro*_*and 3 ruby

红宝石sendmethod().call红宝石之间有区别吗?

1.send(:to_f)
=> 1.0
1.method(:to_f).call
=> 1.0
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*sev 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
Run Code Online (Sandbox Code Playgroud)

结果

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
Run Code Online (Sandbox Code Playgroud)