Skip to content

Instantly share code, notes, and snippets.

@ignisf
Forked from SamSaffron/test.rb
Last active May 4, 2021 23:47
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 ignisf/437cfdcbb4a1da5b142efc90408eeafd to your computer and use it in GitHub Desktop.
Save ignisf/437cfdcbb4a1da5b142efc90408eeafd to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'set'
numbers = (1..10000).to_a
numbers_as_string = "," + (1..10000).to_a.join(",") + ","
numbers_as_set = Set.new(numbers)
Benchmark.ips do |x|
x.report("binary search numbers") do |i|
while i > 0
numbers.bsearch { |x| x == 77 }
i -= 1
end
end
x.report("numbers") do |i|
while i > 0
numbers.include?(5000)
i -= 1
end
end
x.report("string") do |i|
while i > 0
numbers_as_string.include?(",5000,")
i -= 1
end
end
x.report("Set") do |i|
while i > 0
numbers_as_set.include?(5000)
i -= 1
end
end
x.compare!
end
@ignisf
Copy link
Author

ignisf commented May 4, 2021

Warming up --------------------------------------
binary search numbers
                       151.980k i/100ms
             numbers     2.391k i/100ms
              string    20.043k i/100ms
                 Set     1.427M i/100ms
Calculating -------------------------------------
binary search numbers
                          1.527M (± 0.2%) i/s -      7.751M in   5.077015s
             numbers     23.869k (± 1.0%) i/s -    119.550k in   5.009105s
              string    199.463k (± 1.9%) i/s -      1.002M in   5.026418s
                 Set     14.257M (± 0.3%) i/s -     71.341M in   5.004060s

Comparison:
                 Set: 14256733.5 i/s
binary search numbers:  1526686.8 i/s - 9.34x  (± 0.00) slower
              string:   199462.7 i/s - 71.48x  (± 0.00) slower
             numbers:    23868.8 i/s - 597.30x  (± 0.00) slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment