Last active
October 22, 2015 12:31
-
-
Save stillhart/20aa9a1b2eeb0cff4cf5 to your computer and use it in GitHub Desktop.
A try to make rubys Array.uniq faster
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 '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