Is there a difference between send (: method_name) and method (: method_name) .call?

Is there a difference between send

and method().call

in ruby?

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

      

Both look the same to me though.

+3


source to share


1 answer


From your point of view, they do the same. But the c version is method

significantly slower (because it does more behind the scenes things, like creating a method object)

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

      



Result

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

      

+10


source







All Articles