Skip to content

Instantly share code, notes, and snippets.

@salanki
Last active February 7, 2018 06:52
Show Gist options
  • Save salanki/6b8eeaaff711eecd8a81df0eba0d571c to your computer and use it in GitHub Desktop.
Save salanki/6b8eeaaff711eecd8a81df0eba0d571c to your computer and use it in GitHub Desktop.
Performance effects of subtly different ActiveRecord methods

Checking for existance

TL;DR

Use exists?

exits?

Ruby:

irb(main):016:0> User.where("id > ?", 1).exists?
  User Exists (0.9ms)  SELECT  1 AS one FROM "users" WHERE (id > 1) LIMIT 1
=> true

Postgres:

------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.11..0.16 rows=1 width=0) (actual time=0.128..0.128 rows=1 loops=1)
   ->  Index Only Scan using users_pkey on users  (cost=0.11..3958880.39 rows=85465216 width=0) (actual time=0.125..0.125 rows=1 loops=1)
         Index Cond: (id > 1)
         Heap Fetches: 1
 Planning time: 2.707 ms
 Execution time: 0.447 ms
(6 rows)

present?

Ruby:

irb(main):017:0> User.where("id > ?", 1).present?
  User Load (1.8ms)  SELECT "users".* FROM "users" WHERE (id > 1)
=> true

Postgres:

-------- Ungodly slow

any?

Ruby:

irb(main):019:0> User.where("id > ?", 1).any?  
   (1.1ms)  SELECT COUNT(*) FROM "users" WHERE (id > 1)
=> true

Postgres:

postgres=# explain analyze SELECT COUNT(*) FROM "users" WHERE (id > 1);  
                                                                     QUERY PLAN                                                                     
----------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=4001612.99..4001613.00 rows=1 width=0) (actual time=13830.287..13830.287 rows=1 loops=1)
   ->  Index Only Scan using users_pkey on users  (cost=0.11..3958880.39 rows=85465216 width=0) (actual time=0.018..13335.110 rows=5155344 loops=1)
         Index Cond: (id > 1)
         Heap Fetches: 4864391
 Planning time: 0.257 ms
 Execution time: 13830.332 ms
(6 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment