Skip to content

Replace Enumerable#reverse.each with Enumerable#reverse_each#17244

Merged
fxn merged 1 commit intorails:masterfrom
sferik:reverse_each
Oct 13, 2014
Merged

Replace Enumerable#reverse.each with Enumerable#reverse_each#17244
fxn merged 1 commit intorails:masterfrom
sferik:reverse_each

Conversation

@sferik
Copy link
Contributor

@sferik sferik commented Oct 13, 2014

Similar to #17099, Enumerable#reverse allocates an extra array. Enumerable#reverse_each yields each value without allocating an extra array. This is the reason why Enumerable#reverse_each exists. It is also about 17% faster.

Benchmark
require 'benchmark/ips'

ARRAY = (1..100).to_a

def slow
  ARRAY.reverse.each{|x| x}
end

def fast
  ARRAY.reverse_each{|x| x}
end

Benchmark.ips do |x|
  x.report('slow') { slow }
  x.report('fast') { fast }
end
Ruby 2.1.2
slow 156173.2 (±9.2%) i/s - 770040 in 5.009112s
fast 182859.3 (±7.8%) i/s - 914486 in 5.035575s

fxn added a commit that referenced this pull request Oct 13, 2014
Replace Enumerable#reverse.each with Enumerable#reverse_each
@fxn fxn merged commit 85901b4 into rails:master Oct 13, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants