performance

select, pluck

pluck 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)

  1. Preload loads the association data in a separate query.

    Since preload always generates two sql, we can’t use posts table in where condition.

  2. eager_loading loads all association in a single query using LEFT OUTER JOIN.

  3. Includes

    Behaves based on situations, intelligent!

    includes + references = eager_loading

  4. Joins brings 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

http://blog.arkency.com/2013/12/rails4-preloading/

http://collectiveidea.com/blog/archives/2015/03/05/optimizing-rails-for-memory-usage-part-3-pluck-and-database-laziness

Last updated

Was this helpful?