Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Array#shuffle.first with Array#sample #17245

Merged
merged 1 commit into from Oct 13, 2014

Conversation

@sferik
Copy link
Contributor

commented Oct 13, 2014

Similar to #17099, Array#shuffle allocates an extra array. Array#sample indexes into the array without allocating an extra array. This is the reason why Array#sample exists. It is also more than 15X faster.

Benchmark
require 'benchmark/ips'

ARRAY = (1..100).to_a

def slow
  ARRAY.shuffle.first
end

def fast
  ARRAY.sample
end

Benchmark.ips do |x|
  x.report('slow') { slow }
  x.report('fast') { fast }
end
Ruby 2.1.2
slow  324806.7 (±8.1%) i/s - 1620738 in 5.028042s
fast 5069719.9 (±9.5%) i/s - 24872400 in 5.011482s

fxn added a commit that referenced this pull request Oct 13, 2014

Merge pull request #17245 from sferik/sample
Replace Array#shuffle.first with Array#sample

@fxn fxn merged commit 0e08667 into rails:master Oct 13, 2014

1 check passed

continuous-integration/travis-ci The Travis CI build passed
Details
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.