1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Perfomance fix for Enumerable#index_by

Calculating -------------------------------------
              before    34.731k i/100ms
               after    48.206k i/100ms
-------------------------------------------------
              before    508.451k (± 1.2%) i/s -      2.570M
               after    720.068k (± 0.9%) i/s -      3.615M
Comparison:
               after:   720067.6 i/s
              before:   508451.1 i/s - 1.42x slower
This commit is contained in:
lvl0nax 2016-05-13 16:43:01 +03:00
parent b6429b871f
commit 6751b10320

View file

@ -34,7 +34,9 @@ module Enumerable
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
def index_by
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
result = {}
each { |elem| result[yield(elem)] = elem }
result
else
to_enum(:index_by) { size if respond_to?(:size) }
end