Skip to content

Instantly share code, notes, and snippets.

@ebakan
Last active March 2, 2017 01:28
Show Gist options
  • Save ebakan/38d7a1802a7fee10071e3baf2cf562ef to your computer and use it in GitHub Desktop.
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?
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
@ebakan
Copy link
Author

ebakan commented Mar 2, 2017

RESULTS:
1 element(s):   Set: 4.7999899834394455e-05     Array: 2.00001522898674e-06     Winner: Array
10 element(s):  Set: 9.999843314290047e-06      Array: 2.00001522898674e-06     Winner: Array
100 element(s): Set: 4.0999846532940865e-05     Array: 4.000007174909115e-05    Winner: Array
110 element(s): Set: 4.600011743605137e-05      Array: 4.5999884605407715e-05   Winner: Array
125 element(s): Set: 4.900014027953148e-05      Array: 5.7999975979328156e-05   Winner: Set
150 element(s): Set: 5.8999983593821526e-05     Array: 8.099991828203201e-05    Winner: Set
200 element(s): Set: 8.200015872716904e-05      Array: 0.00013999990187585354   Winner: Set
250 element(s): Set: 0.00010199984535574913     Array: 0.00027900002896785736   Winner: Set
500 element(s): Set: 0.00023999996483325958     Array: 0.0007879999466240406    Winner: Set
1000 element(s):        Set: 0.0004210001789033413      Array: 0.003202000167220831     Winner: Set
10000 element(s):       Set: 0.004206999903544784       Array: 0.2826050000730902       Winner: Set

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