2016-01-18 40 views
1

以下哪個查詢的成本最低?以下哪個查詢的成本最低?

A.

def recent_followers 
    self.followers.recent.includes(:user).collect {|f| f.user.name }.to_sentence 
end 

B.

Select followers where user_id = 1 

Select users where user_id in (2,3,4,5) 
+1

我建議'的https:// github.com/MiniProfiler /機架迷你profiler'

,你可以重寫你的第一次嘗試。它會告訴你每個查詢的時間和更多有用的信息! :) –

回答

0

數據庫查詢總是快,比Ruby處理。

您的第一個選項使用collect,這有一個缺點,因爲它必須在處理之前將整個集合加載到內存中。

followers.recent.joins(:user).pluck('users.name') # no need for self, btw