How are you checking existing a record?
present? any? empty? exists?
Let's check SQL queries
1. present? loads all the records from the database into memory and then checks</div>
2. any? & empty? identical requests but opposite results. They are better, because load COUNT(*) of records.
3. exists? The best way. Is even more optimized. It uses the SELECT 1
Example
present? => 2892.7 ms
any? => 400.9 ms
empty? => 403.9 ms
exists? => 1.1 ms
Exception
For example, if we are checking for the existence of an association record without any scope, any? and empty? will also produce a very optimized query that uses SELECT 1 FROM ... LIMIT 1 form, but any? fill not hit the database again if the records are already loaded into memory.
semaphoreci.com
Comments
Post a Comment