Skip to content

Instantly share code, notes, and snippets.

@shanemcd
Created November 13, 2012 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanemcd/4066669 to your computer and use it in GitHub Desktop.
Save shanemcd/4066669 to your computer and use it in GitHub Desktop.
Benchmarks when removing duplicate items from array
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