http://ujihisa.nowa.jp/entry/67a15ef440
Experiment
require 'benchmark' module Enumerable def my_mins_by(&block) min = min_by(&block) select {|e| e == min } end def uj_mins_by(&b) memo = [] memo_value = 1/0.0 each do |e| value = yield e if value < memo_value memo = [e] memo_value = value elsif value == memo_value memo << e end end memo end end target = 1000.times.map { rand 10 } - [0] Benchmark.bmbm do |x| x.report('my') { target.my_mins_by {|e| e ** 2 } } x.report('uj') { target.uj_mins_by {|e| e ** 2 } } end
Result
Rehearsal -------------------------------------- my 0.000000 0.000000 0.000000 ( 0.000808) uj 0.000000 0.000000 0.000000 ( 0.001566) ----------------------------- total: 0.000000sec user system total real my 0.010000 0.000000 0.010000 ( 0.000773) uj 0.000000 0.000000 0.000000 ( 0.000940)
Consider
直感的には僕の方が遅くなりそうなのに。