Skip to content

Instantly share code, notes, and snippets.

@stillhart
Last active October 22, 2015 12:31
Show Gist options
  • Save stillhart/20aa9a1b2eeb0cff4cf5 to your computer and use it in GitHub Desktop.
Save stillhart/20aa9a1b2eeb0cff4cf5 to your computer and use it in GitHub Desktop.
A try to make rubys Array.uniq faster
require 'digest'
require 'benchmark'
list = (1..100000).to_a.map(&:to_s).map {|e| Digest::SHA256.hexdigest(e)}
list += list
list.shuffle
def hash_uniq(a)
a_hash = {}
a.each do |v|
a_hash[v] = nil
end
a_hash.keys
end
Benchmark.bm do |x|
x.report(:uniq) { 100.times { list.uniq} }
x.report(:hash_uniq) { 100.times { hash_uniq(list) } }
end
puts "Results are the same" if list.uniq == hash_uniq(list)
# user system total real
# uniq 23.750000 0.040000 23.790000 ( 23.823770)
# hash_uniq 18.560000 0.020000 18.580000 ( 18.591803)
# Results are the same
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment