这个问题源于我做了 2 种类型的 performance 调整:
- 将我的许多
where().present?
语句更改为where().exists?
- 将我的很多
where().first
更改为find_by()
坐在这的交叉点是我以前写过 .where().first.present?
的情况,我想知道将其更改为: .find_by().present?
或 .where().exists?
会更有性能
回答1
- 将
where().present?
更改为where().exists?
where().present?
或 find_by().present?
将始终从 table 获取完整的用户记录:
SELECT * FROM xyz WHERE xyz.name = 'Deepesh'
而 where().exists?
或 where().any?
将运行此查询:
SELECT 1 FROM xyz WHERE xyz.name = 'Deepesh' LIMIT 1
因此,显然 exists?
或 any?
在 performance 方面会更好,直到您需要检查该记录以获取一些信息或在某处使用它,例如:
user = User.find_by(name: 'Deepesh')
user.do_something if user.present?
所以在这里你需要对该用户执行一些操作,如果记录存在,那么使用 present?
将是明智的。
注意:我们使用 exists?
节省的时间将是初始化 ActiveRecord
对象,present?
将初始化一个,而 exists
不会。在此处阅读更多信息:https://stackoverflow.com/a/30192978/4207394