.exists 之间的性能差异?和.where.present?
Performance differences between .exists? and .where.present?
以下两个选项之间存在哪些性能差异(如果有)mentioned in this answer)
Thing.where(name: "Bob").present?
产生 SQL
SELECT COUNT(*) FROM things WHERE things.name = "Bob";
和
Thing.exists?(name: "Bob")
产生 SQL
SELECT 1 AS one from things WHERE name ="Bob" limit 1;
由于 SQL 语句不同,理论上可能存在性能差异。但我不知道,假设 name
在数据库中被索引,是否有任何实际差异。此外,在 Ruby 领域(例如初始化和 GC)中完成的工作量是否有任何差异。
如果有什么不同,我正在使用 Rails 3.2.20.
您可以像这样自己做基准测试:
$ bin/rails c
> ids = Item::Project.pluck(:id)
> b = Benchmark.bmbm do |x|
> x.report("present?") { 10000.times { Item::Project.where(id: ids.sample).present? } }
> x.report("exist?") { 10000.times { Item::Project.exists?(id: ids.sample) } }
> end
> puts b
4.650000 0.270000 4.920000 ( 7.627897)
4.660000 0.330000 4.990000 ( 7.337031)
id 由数据库索引。如果我选择一个没有索引的列,结果如下所示:
12.590000 0.740000 13.330000 ( 71.199677)
8.350000 0.620000 8.970000 ( 34.846301)
这个 table 大约有 30000 条记录。所以 present? 比 exist? 慢,因为它必须首先计算所有匹配的记录。
以下两个选项之间存在哪些性能差异(如果有)mentioned in this answer)
Thing.where(name: "Bob").present?
产生 SQL
SELECT COUNT(*) FROM things WHERE things.name = "Bob";
和
Thing.exists?(name: "Bob")
产生 SQL
SELECT 1 AS one from things WHERE name ="Bob" limit 1;
由于 SQL 语句不同,理论上可能存在性能差异。但我不知道,假设 name
在数据库中被索引,是否有任何实际差异。此外,在 Ruby 领域(例如初始化和 GC)中完成的工作量是否有任何差异。
如果有什么不同,我正在使用 Rails 3.2.20.
您可以像这样自己做基准测试:
$ bin/rails c
> ids = Item::Project.pluck(:id)
> b = Benchmark.bmbm do |x|
> x.report("present?") { 10000.times { Item::Project.where(id: ids.sample).present? } }
> x.report("exist?") { 10000.times { Item::Project.exists?(id: ids.sample) } }
> end
> puts b
4.650000 0.270000 4.920000 ( 7.627897)
4.660000 0.330000 4.990000 ( 7.337031)
id 由数据库索引。如果我选择一个没有索引的列,结果如下所示:
12.590000 0.740000 13.330000 ( 71.199677)
8.350000 0.620000 8.970000 ( 34.846301)
这个 table 大约有 30000 条记录。所以 present? 比 exist? 慢,因为它必须首先计算所有匹配的记录。