Skip to main content

present-vs-exists-first-vs-take-count-vs-size-and-writing-efficient-ruby

.present? vs .exists?​

In short: if you are checking if something exists in the database, use .exists?. Using .present? will cause DB to look through all rows that match the condition and is MUCH slower

present? =>  2892.7 ms
any? => 400.9 ms
empty? => 403.9 ms
exists? => 1.1 ms

Read this for more detail and examples: https://semaphoreci.com/blog/2017/03/14/faster-rails-how-to-check-if-a-record-exists.html

.first vs .take​

In short: .take is faster because it returns the first record it finds with the given condition. Only use .first if you need a result with a specific order.

first: Find the first record (or first N records if a parameter is supplied). If no order is defined it will order by primary key.

take: Gives a record (or N records if a parameter is supplied) without any implied order. The order will depend on the database implementation. If an order is supplied it will be respected

Read this for more detail: https://stackoverflow.com/questions/18496421/take-vs-first-performance-in-ruby-on-rails

.count vs .size​

In short: always use .size unless you need the DB to perform a SQL count right now

size: If the query is already loaded, it will get the count without having to run another SQL query

count: will always try to execute a SQL query, every time

Read this for more detail: https://www.speedshop.co/2019/01/10/three-activerecord-mistakes.html