method_missingは重いのか?
レシーバに該当するメソッドが定義されておらずmethod_missingが実行された場合、通常のメソッド呼び出しと比べて遅くなったりするのか測ってみました。
結論
たいして変わりません。
計測コード
プロファイラを使ってみました。
- 通常のメソッド呼び出し
- method_missingの呼び出し
をそれぞれ10000回実行し所用時間を計測します。
require 'profiler' class Kitten def initialize( name ) @name = name; end # 普通のメソッド def name @name end # method_missing。処理内容は普通のメソッドと同じ def method_missing( name, *args ) @name end end mii = Kitten.new("mii") # 普通のメソッド Profiler__.start_profile 10000.times() {|i| mii.name } Profiler__.stop_profile Profiler__.print_profile(STDOUT) # method_missing Profiler__.start_profile 10000.times() {|i| mii.not_found } Profiler__.stop_profile Profiler__.print_profile(STDOUT)
実行結果です。
% cumulative self self total time seconds seconds calls ms/call ms/call name 56.63 0.49 0.49 10000 0.05 0.05 Kitten#name 43.37 0.86 0.37 1 373.00 860.00 Integer#times 0.00 0.86 0.00 1 0.00 860.00 #toplevel % cumulative self self total time seconds seconds calls ms/call ms/call name 51.88 0.47 0.47 10000 0.05 0.05 Kitten#method_missing 48.12 0.91 0.44 1 436.00 906.00 Integer#times 0.00 0.91 0.00 1 0.00 906.00 #toplevel