25 February 2014
Don’t use Array#include? as a lookup table. Set#include? is way faster.
Array#include?
Set#include?
Here’s an example where it’s 150X faster:
require 'benchmark/ips' require 'set' ary = [] 5000.times { ary << rand.round(6) } set = ary.to_set Benchmark.ips do |x| x.report("Array#include?") { ary.include?(rand.round(6))} x.report("Set#include?") { set.include?(rand.round(6))} end
And the benchmarking results:
Calculating ------------------------------------- Array#include? 374 i/100ms Set#include? 60669 i/100ms ------------------------------------------------- Array#include? 3780.7 (±1.1%) i/s - 19074 in 5.045665s Set#include? 2078044.8 (±3.5%) i/s - 10374399 in 5.000050s