performance
select, pluck
select, pluckpluck will load an array of column, and is faster than select.
select is ~10X slower than pluck, because of creating objects.
User.select(:id).to_a
# => User Load (0.9ms) SELECT id FROM "users"
# => [#<User id: 12>, #<User id: 42>, #<User id: 1>, #<User id: 24>, #<User id: 200>, ...]User.pluck(:id)
# => (0.9ms) SELECT "users"."id" FROM "users"
# => [12, 42, 1, 24, 200, ..., 365]
User.pluck(:first_name, :last_name, :email)
# => (2.2ms) SELECT "users"."first_name", "users"."last_name", "users"."email" FROM "users"
# => [[nil, nil, "jeff@gmail.com"], ['joe', nil, "joe.brown@gmail.com"], ["Edward", "Stanza", "ed@email.com"], ...]http://gavinmiller.io/2013/getting-to-know-pluck-and-select/
How long to build ActiveRecord models
10.4ms for db query, but total 143ms for the whole process.
User.all.to_a
# => User Load (10.4ms) SELECT "users".* FROM "users"
# => [#<User id: 263, ... >, #<User id: 264, ... >, #<User id: 265, ... >, ... ]
puts Benchmark.measure { User.all.to_a }
user system total real
0.143333 0.000000 0.143333 ( 0.163123)Preload, Eagerload, Includes and Joins
preload, eager_load, includes = eager loading (prevent n+1)
Preloadloads the association data in a separate query.Since
preloadalways generates two sql, we can’t use posts table in where condition.eager_loadingloads all association in a single query using LEFT OUTER JOIN.IncludesBehaves based on situations, intelligent!
includes+references=eager_loadingJoinsbrings association data using inner join.
Intention for eager loading
Too much query
Array
DB query
sort_by
order
.select { c c.label != 'All' }
.where.not(label: 'All')
http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html
Last updated
Was this helpful?