简体   繁体   中英

Rails 5 - first vs where limit 1 vs find

Using Benchmark ips I did this testing. Correct me if I'm wrong in what I just tested. Note that 96 is the id of the first user in my db.

Benchmark.ips do |x|
  x.report("first") do
    User.first
  end
  x.report("where") do
    User.where(id: 96).limit(1)
  end
  x.report("find") do
    User.find(96)
  end
  x.compare!
end

I ran this test several times and got this as result

Comparison:
               where:    26430.8 i/s
               first:      999.8 i/s - 26.44x  slower
                find:      964.3 i/s - 27.41x  slower

My conclussion of this is to always use where instead of find or first as these are much slower ways to get a specific user.

Rails 5.0.0.1, PostgreSQL 9.5.3, Ruby 2.3.1

As Michael Chaney points out in the comments, the line

User.where(id: 96).limit(1)

does NOT execute the query, it just builds an ActiveRecord_Relation which is only executed when you attempt to access the user record(s) it relates to.

This is why you can build a query over several lines with minimal performance impact

  @users = User.where(type: 'admin')
  @users = @users.where(status: 'enabled')

It's only when you iterate through the @users that the query with the where clause "type = 'admin AND status = 'enabled'" executes.

Try the benchmarks again but (as Michael suggests) change the relation into an array which will execute the query.

User.where(id: 96).limit(1).to_a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM