Caching with instance variable

A performance trick that use to improve the performance and store the end result of expensive command in an a instance variable.

Take a look to below code..

def unread_message
    @unread_message ||= Message.all(conditions: { :to => fbauth.uid , :isRead => 0 })

That means the first time you call unread_message, one db query will be sent, get all unread message of current facebook logged in user  , then assign the result to the instance variable @unread_message. The second time you call unread_message, no  query be sent OR execute, just return the @unread_message directly.



One thought on “Caching with instance variable

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s