ベンチマーク:値の参照いろいろ
微妙に気になったのでベンチマークを採ってみました。ある値を参照したい時に、定数を参照するのと関数(メソッド)の返り値として値を得るのでは、どのくらい差があるのでしょうか。とっても素朴な疑問ですが、測ってみたことがないのでやってみました。
require "benchmark" TEST = 1 def test 1 end count = 1000_0000 Benchmark.bmbm do |x| x.report("empty"){1.upto(count){}} x.report("literal"){1.upto(count){1}} x.report("constant"){1.upto(count){TEST}} x.report("function"){1.upto(count){test}} end
結果は次のようになりました。
Rehearsal -------------------------------------------- empty 1.690000 0.010000 1.700000 ( 2.047236) literal 3.300000 0.650000 3.950000 ( 4.010947) constant 3.670000 0.670000 4.340000 ( 4.363239) function 6.730000 1.430000 8.160000 ( 8.212460) ---------------------------------- total: 18.150000sec user system total real empty 1.280000 0.000000 1.280000 ( 1.300398) literal 3.250000 0.760000 4.010000 ( 4.187584) constant 3.650000 0.680000 4.330000 ( 4.384728) function 6.850000 1.320000 8.170000 ( 8.225316)
てなわけで、1000万回参照する時でやっと数秒程度、という感じみたいです(定数の方が大体2倍くらい速い?)。もっと差が開くのかと思ったのに。