Skip to content

Instantly share code, notes, and snippets.

@deepak
Last active June 30, 2016 06:10
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 deepak/441b1db42b2a83e2f689d79c8266f2be to your computer and use it in GitHub Desktop.
Save deepak/441b1db42b2a83e2f689d79c8266f2be to your computer and use it in GitHub Desktop.
ruby unique inserts using Set and Array
require 'benchmark'
require 'set'
NUMBERS = 5000.times.collect { rand(10) }
Benchmark.bmbm do |x|
x.report("set") do
set = Set.new
NUMBERS.each do |number|
set.add number
end
set.to_a
end
x.report("array-uniq") do
array = []
NUMBERS.each do |number|
array << number
end
array.uniq
end
x.report("array-uniq!") do
array = []
NUMBERS.each do |number|
array << number
end
array.uniq!
end
end
__END__
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin14.0]
Rehearsal -----------------------------------------------
set 0.000000 0.000000 0.000000 ( 0.001033)
array-uniq 0.000000 0.000000 0.000000 ( 0.000716)
array-uniq! 0.000000 0.000000 0.000000 ( 0.000682)
-------------------------------------- total: 0.000000sec
user system total real
set 0.000000 0.000000 0.000000 ( 0.000970)
array-uniq 0.000000 0.000000 0.000000 ( 0.000751)
array-uniq! 0.000000 0.000000 0.000000 ( 0.000704)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment