[Ruby] Which is faster, Array#sample or Random#rand?

less than 1 minute read

If you want to loop a few hundred thousand times in batch processing and choose a random number each time, I was wondering which one of Array#sample and Random#rand has better performance, so I checked ..

Immediately below measurement

range = (1..10000)
array = range.to_a
num = 1000000

Benchmark.bm 10 do |r|
   r.report'Array#sample' do
     num.times do
       array.sample
     end
   end

   r.report'Random#rand' do
     num.times do
       rand(range)
     end
   end
end

Result is

                  user system total real
Array#sample 0.114216 0.002376 0.116592 (0.120891)
Random#rand 0.198875 0.001285 0.200160 (0.206403)

So Array#sample was slightly faster. However, this time it may be because range is passed, but it may be because it is doing to_a internally…

Tags:

Updated: