Skip to content

Instantly share code, notes, and snippets.

@kirs
Last active February 26, 2017 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirs/11ba4ce84c08188c9f7eba9c639616a5 to your computer and use it in GitHub Desktop.
Save kirs/11ba4ce84c08188c9f7eba9c639616a5 to your computer and use it in GitHub Desktop.
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