Last active
March 2, 2017 01:28
-
-
Save ebakan/38d7a1802a7fee10071e3baf2cf562ef to your computer and use it in GitHub Desktop.
If I have an n-element array and I want to test element inclusion n times, is it faster to use Array#includes? or create a set and use Set#includes?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'set' | |
[1, 10, 100, 110, 125, 150, 200, 250, 500, 1000, 10000].each do |i| | |
arr = (0..i).to_a.shuffle | |
set_time = Benchmark.realtime do | |
set = Set.new arr | |
i.times do |j| | |
set.include? j | |
end | |
end | |
arr_time = Benchmark.realtime do | |
i.times do |j| | |
arr.include? j | |
end | |
end | |
puts "#{i} element(s):\tSet: #{set_time}\tArray: #{arr_time}\tWinner: #{set_time > arr_time ? "Array" : "Set"}" | |
end |
Author
ebakan
commented
Mar 2, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment