簡體   English   中英

Rails,是 find_by().present 嗎? 比 where().exists 更高效?

[英]Rails, is find_by().present? more performant than where().exists?

這個問題源於我做了兩種性能調整:

  • 改變了很多我的where().present? where().exists?
  • 將我的很多where().first更改為find_by()

坐在這個的交叉點是我之前寫過.where().first.present? 我想知道將其更改為.find_by().present? .where().exists?

  • 改變where().present? where().exists?

where().present? 還是find_by().present? 將始終從表中獲取完整的用戶記錄:

SELECT * FROM xyz WHERE xyz.name = 'Deepesh'

where().exists? where().any? 將運行此查詢:

SELECT 1 FROM xyz WHERE xyz.name = 'Deepesh' LIMIT 1

這么明顯exists? any? 在您需要正在檢查的記錄以獲取某些信息或在某處​​使用它之前,性能會更好,例如:

user = User.find_by(name: 'Deepesh')
user.do_something if user.present?

所以在這里你需要對該用戶執行一些操作,如果記錄存在然后使用present? 會是明智的。

注意:我們將節省使用的時間exists? 會是ActiveRecord對象的初始化present? 會初始化一個,而exists不會。 在此處閱讀更多信息: https ://stackoverflow.com/a/30192978/4207394

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM