Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Last active September 17, 2015 03:40
Show Gist options
  • Save amitpatelx/bd47d07a303956ba8b56 to your computer and use it in GitHub Desktop.
Save amitpatelx/bd47d07a303956ba8b56 to your computer and use it in GitHub Desktop.
blank? vs empty? - ActiveRecord

blank? will load the entire array, then check to see if the array is empty.

On the other hand, empty? asks the database for a count, and checks to see if that count is zero or not. This might not make a difference in small datasets (like development), but it can make a big difference in databases with large datasets (like production).

It will also make a huge difference in memory consumption when thousands of records are loaded vs a single integer.

Reference:

http://hashrocket.com/blog/posts/rails-quick-tips-easy-activerecord-optimizations

User.where(screen_name: ['user1','user2']).blank?
# 1. Queries database for all user data
# SELECT "users".* FROM "users" WHERE "users"."screen_name" IN ('user1','user2')
# 2. Loads users into an array
# [<#User:0x007fbf6413c510>,<#User:0x007fbf65ab1c70>]
# 3. Checks to see if the array size is zero
# => true
# Using `empty?`
User.where(screen_name: ['user1','user2').empty?
# 1. Queries database for ONLY a count
# SELECT COUNT(*) FROM "users" WHERE "users"."screen_name" IN ('user1','user2')
# 2. Checks to see if the count is zero
# => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment