Skip to content

Instantly share code, notes, and snippets.

@czj
Created June 23, 2020 10:16
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 czj/2f991c2886b1104f267fa9e715c885cc to your computer and use it in GitHub Desktop.
Save czj/2f991c2886b1104f267fa9e715c885cc to your computer and use it in GitHub Desktop.
Ruby Array versus Set performance test
# frozen_string_literal: true
require "benchmark"
array = [4, 5, 6, 11, 12, 20, 40, 64, 65, 66, 81, 83].freeze
set = Set.new(array).freeze
n = 10_000_000
Benchmark.bm(7) do |x|
x.report("array found at position 0") { n.times { array.include?(4) } }
x.report("set found at position 0") { n.times { set.include?(4) } }
x.report("array found at position 3") { n.times { array.include?(4) } }
x.report("set found at position 3") { n.times { set.include?(4) } }
x.report("array found at position 6") { n.times { array.include?(20) } }
x.report("set found at position 6") { n.times { set.include?(20) } }
x.report("array found at position 12") { n.times { array.include?(83) } }
x.report("set found at position 12") { n.times { set.include?(83) } }
end && "OK"

Unless you have a VERY small array, always use Set :)

array found at position 0 0.430831 0.000121 0.430952 ( 0.431130)
set found at position 0 0.500662 0.000286 0.500948 ( 0.501336)
array found at position 3 0.427675 0.000127 0.427802 ( 0.427939)
set found at position 3 0.496058 0.000214 0.496272 ( 0.496377)
array found at position 6 0.647587 0.000124 0.647711 ( 0.647845)
set found at position 6 0.499261 0.000456 0.499717 ( 0.500244)
array found at position 12 0.919871 0.000421 0.920292 ( 0.920593)
set found at position 12 0.498176 0.000177 0.498353 ( 0.498576)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment