send vs method.call

  • 個人的には method.call が明示的な感じがして好み
  • でも場面で使い分けるべきもののような気もする・・?
  • パフォーマンスは確かメソッドの方が高かったような・・2009年ぐらいの記事で見た記憶・・
  • sendはプライベートメソッドも問答無用で呼べる
  • method_missing を定義している?
    • method.call は undefined method エラー
    • sendmethod_missingが呼ばれる

パフォーマンスは確かメソッドの方が高い

んなこたーなかった。

require 'benchmark'

test = "i love method call"
# m    = test.method(:length)
n    = 100000

Benchmark.bmbm do |x|
  x.report('call') { n.times { test.method(:length).call } }
  x.report('send') { n.times { test.send(:length) } }
end
Rehearsal ----------------------------------------
call   0.070000   0.000000   0.070000 (  0.074462)
send   0.010000   0.000000   0.010000 (  0.010076)
------------------------------- total: 0.080000sec

           user     system      total        real
call   0.060000   0.000000   0.060000 (  0.069770)
send   0.020000   0.000000   0.020000 (  0.011436)

当然っちゃ当然だけどMethodオブジェクトをキャッシュすると速くなる

require 'benchmark'

test = "i love method call"
m    = test.method(:length)
n    = 100000

Benchmark.bmbm do |x|
  x.report('call') { n.times { m.call } }
  x.report('send') { n.times { test.send(:length) } }
end
Rehearsal ----------------------------------------
call   0.010000   0.000000   0.010000 (  0.011799)
send   0.010000   0.000000   0.010000 (  0.010710)
------------------------------- total: 0.020000sec

           user     system      total        real
call   0.010000   0.000000   0.010000 (  0.012099)
send   0.010000   0.000000   0.010000 (  0.010251)

なんとなくsendはプライベートメソッドも呼べるのが嫌な感じがする・・ public_sendはまあ、使わないよね・・

割りと抽象度を高めると、method(:hoge).callのほうが何をしているのかわかりやすい気がする