From 030d2260a737a08b967eb5cd2d46205f7e315571 Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 9 Sep 2013 16:02:13 +1000 Subject: [PATCH] Perf: don't allocate hashes OVER and OVER in a loop, its bad --- lib/avatar_lookup.rb | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/avatar_lookup.rb b/lib/avatar_lookup.rb index c48ee5cd2..aef319692 100644 --- a/lib/avatar_lookup.rb +++ b/lib/avatar_lookup.rb @@ -11,11 +11,28 @@ class AvatarLookup private + def self.lookup_columns + @lookup_columns ||= [:id, + :email, + :username, + :use_uploaded_avatar, + :uploaded_avatar_template, + :uploaded_avatar_id] + end + def users - @users ||= User.where(:id => @user_ids) - .select([:id, :email, :username, :use_uploaded_avatar, :uploaded_avatar_template, :uploaded_avatar_id]) - .inject({}) do |hash, user| - hash.merge({user.id => user}) - end + @users ||= user_lookup_hash + end + + def user_lookup_hash + # adding tap here is a personal taste thing + hash = {} + User + .where(:id => @user_ids) + .select(AvatarLookup.lookup_columns) + .each{|user| + hash[user.id] = user + } + hash end end