Premature optimisation in my Rails session code?

For years and years, I've been writing


def current_user
  @current_user ||= (session[:user_id] && User.find_by_id(session[:user_id]))
end 


The idea was to look up and store the current user object in an instance variable the frst time the method was called, and then use the value in that variable for subsequent calls in the same request. 


But now I'm thinking I'll just write this:


def current_user
  session[:user_id] && User.find_by_id(session[:user_id])
end 


Rails already caches query results, so although the find() method will be called on every call to current_user(), the database will only be accessed once, and the user object will only be constructed once. Why complicate my code with optimizations if I haven't yet identified the performance of this method to be an issue?


Is that reckless of me? Or is the ||= a premature optimization which I should train myself out of?


 

1 like ·   •  0 comments  •  flag
Share on Twitter
Published on July 18, 2012 11:21
No comments have been added yet.