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