And*_*imm 4 performance ruby-on-rails ruby-on-rails-3 rails-activerecord
以下两个选项之间存在哪些性能差异(如果有的话)(在本回答中提到)
Thing.where(name: "Bob").present?
Run Code Online (Sandbox Code Playgroud)
它产生SQL
SELECT COUNT(*) FROM things WHERE things.name = "Bob";
Run Code Online (Sandbox Code Playgroud)
和
Thing.exists?(name: "Bob")
Run Code Online (Sandbox Code Playgroud)
它产生SQL
SELECT 1 AS one from things WHERE name ="Bob" limit 1;
Run Code Online (Sandbox Code Playgroud)
由于SQL语句不同,理论上可能存在性能差异.但我不知道,假设name在数据库中编入索引,是否存在任何实际差异.此外,在Ruby-land中完成的工作量(例如初始化和GC)是否有任何差异.
如果它有任何区别,我正在使用Rails 3.2.20.
小智 7
您可以像这样自己做基准测试:
$ 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)
Run Code Online (Sandbox Code Playgroud)
id由数据库索引.如果我选择一个未编制索引的列,结果如下所示:
12.590000 0.740000 13.330000 ( 71.199677)
8.350000 0.620000 8.970000 ( 34.846301)
Run Code Online (Sandbox Code Playgroud)
此表有大约30000条记录.那么礼物?比存在慢?因为它必须先计算所有匹配的记录.
| 归档时间: |
|
| 查看次数: |
1021 次 |
| 最近记录: |