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

Merge pull request #33074 from lsylvester/optimize-pluck

Reduce Memory Allocation when using .pluck
This commit is contained in:
Rafael França 2018-06-19 15:18:35 -04:00 committed by GitHub
commit 897946f214
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 5 deletions

View file

@ -97,12 +97,21 @@ module ActiveRecord
end
def cast_values(type_overrides = {}) # :nodoc:
types = columns.map { |name| column_type(name, type_overrides) }
result = rows.map do |values|
types.zip(values).map { |type, value| type.deserialize(value) }
end
if columns.one?
# Separated to avoid allocating an array per row
columns.one? ? result.map!(&:first) : result
type = column_type(columns.first, type_overrides)
rows.map do |(value)|
type.deserialize(value)
end
else
types = columns.map { |name| column_type(name, type_overrides) }
rows.map do |values|
Array.new(values.size) { |i| types[i].deserialize(values[i]) }
end
end
end
def initialize_copy(other)

View file

@ -642,6 +642,18 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal [ topic.written_on ], relation.pluck(:written_on)
end
def test_pluck_with_type_cast_does_not_corrupt_the_query_cache
topic = topics(:first)
relation = Topic.where(id: topic.id)
assert_queries 1 do
Topic.cache do
kind = relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on).class
relation.pluck(:written_on)
assert_kind_of kind, relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on)
end
end
end
def test_pluck_and_distinct
assert_equal [50, 53, 55, 60], Account.order(:credit_limit).distinct.pluck(:credit_limit)
end