Which is faster, Array # sample or Random # rand?

If you want to loop hundreds of thousands of times in batch processing and choose a random number each time, I was wondering which one is better, ʻArray # sample or Random # rand`, so I checked it. ..

Immediately measure below

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 # samplewas slightly faster. However, this time I'm passingrange, maybe because I'm doing to_a` internally ...

Recommended Posts

Which is faster, Array # sample or Random # rand?
Which is faster, method reference or lambda expression
Java: The problem of which is faster, stream or loop
Which is faster, size or 0, as the argument of List # toArray?
Array is object
Which is better, Kotlin or Java in the future?
The question of which is better, if or switch