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 passing
range, maybe because I'm doing
to_a` internally ...
Recommended Posts