Created
November 13, 2012 16:11
-
-
Save shanemcd/4066669 to your computer and use it in GitHub Desktop.
Benchmarks when removing duplicate items from array
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' | |
arr1 = (1..5000).to_a | |
arr2 = (1..10000).to_a | |
a = arr1.zip(arr2).flatten # 10000 items, 5000 duplicates | |
# with #uniq | |
puts Benchmark.measure { a.uniq } | |
# Total time | |
# => 0.000000 0.000000 0.000000 ( 0.001759) | |
# with #each | |
puts Benchmark.measure { | |
counts = Hash.new(0) | |
a.each { |v| counts[v] += 1 } | |
counts.select { |v, count| count == 1 }.keys | |
} | |
# Total time | |
# => 0.000000 0.000000 0.000000 ( 0.003177) | |
# with inject: | |
puts Benchmark.measure { a.inject([]) { |arr, i| arr << i unless arr.include? i; arr } } | |
# Total time | |
# => 0.920000 0.000000 0.920000 ( 0.923349) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment