Skip to content

Instantly share code, notes, and snippets.

@kirs kirs/compare.rb
Last active Feb 26, 2017

Embed
What would you like to do?
require 'benchmark/ips'
collection = 100.times.map { rand(10) }
TABLE = {
6 => true,
7 => true,
8 => true,
9 => true,
11 => true
}
Benchmark.ips do |x|
x.report "Fixnum#compare" do
collection.each do |c|
(c >= 6 && c <= 9) || c == 11
end
end
x.report "hash lookup" do
collection.each do |c|
TABLE.key?(c)
end
end
x.report "two whens" do
collection.each do |c|
case c
when 6, 7, 8, 9, 11
true
else
false
end
end
end
x.report "multiple whens" do
collection.each do |c|
case c
when 6
true
when 7
true
when 8
true
when 9
true
when 11
true
else
false
end
end
end
x.compare!
end
Warming up --------------------------------------
Fixnum#compare 12.370k i/100ms
hash lookup 12.527k i/100ms
two whens 16.199k i/100ms
multiple whens 15.754k i/100ms
Calculating -------------------------------------
Fixnum#compare 152.121k (± 9.0%) i/s - 754.570k in 5.005868s
hash lookup 129.428k (± 6.6%) i/s - 651.404k in 5.057921s
two whens 130.044k (±25.9%) i/s - 599.363k in 5.017069s
multiple whens 151.871k (±11.9%) i/s - 756.192k in 5.060006s
Comparison:
Fixnum#compare: 152121.5 i/s
multiple whens: 151870.7 i/s - same-ish: difference falls within error
two whens: 130043.5 i/s - same-ish: difference falls within error
hash lookup: 129427.9 i/s - 1.18x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.