Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 5-第一个vs,其中限制1 vs查找_Ruby On Rails_Benchmarking_Ruby On Rails 5 - Fatal编程技术网

Ruby on rails Rails 5-第一个vs,其中限制1 vs查找

Ruby on rails Rails 5-第一个vs,其中限制1 vs查找,ruby-on-rails,benchmarking,ruby-on-rails-5,Ruby On Rails,Benchmarking,Ruby On Rails 5,我使用了这个测试。如果我刚才测试的错误,请纠正我。请注意,96是my db中第一个用户的id Benchmark.ips do |x| x.report("first") do User.first end x.report("where") do User.where(id: 96).limit(1) end x.report("find") do User.find(96) end x.compare! end 我做了几次测试,结果都是这

我使用了这个测试。如果我刚才测试的错误,请纠正我。请注意,96是my db中第一个用户的id

Benchmark.ips do |x|
  x.report("first") do
    User.first
  end
  x.report("where") do
    User.where(id: 96).limit(1)
  end
  x.report("find") do
    User.find(96)
  end
  x.compare!
end
我做了几次测试,结果都是这样

Comparison:
               where:    26430.8 i/s
               first:      999.8 i/s - 26.44x  slower
                find:      964.3 i/s - 27.41x  slower
我的结论是总是使用where而不是find或first,因为这是获得特定用户的慢得多的方法


Rails 5.0.0.1、PostgreSQL 9.5.3、Ruby 2.3.1

正如Michael Chaney在评论中指出的那样

User.where(id: 96).limit(1)
不执行查询,它只是构建一个
ActiveRecord\u关系
,仅当您尝试访问与之相关的用户记录时才会执行该关系

这就是为什么可以在多行上构建查询,而对性能的影响最小

  @users = User.where(type: 'admin')
  @users = @users.where(status: 'enabled')
只有在遍历
@users
时,才会执行带有
where
子句
“type='admin AND status='enabled'”
的查询

再次尝试基准测试,但(正如Michael所建议的)将关系更改为将执行查询的数组

User.where(id: 96).limit(1).to_a

正如迈克尔·切尼在评论中指出的,这句话

User.where(id: 96).limit(1)
不执行查询,它只是构建一个
ActiveRecord\u关系
,仅当您尝试访问与之相关的用户记录时才会执行该关系

这就是为什么可以在多行上构建查询,而对性能的影响最小

  @users = User.where(type: 'admin')
  @users = @users.where(status: 'enabled')
只有在遍历
@users
时,才会执行带有
where
子句
“type='admin AND status='enabled'”
的查询

再次尝试基准测试,但(正如Michael所建议的)将关系更改为将执行查询的数组

User.where(id: 96).limit(1).to_a

您实际上并没有运行“where”查询。如果您在其末尾添加一个
。\u一个
,它可能会实际运行。您实际上没有运行“where”查询。如果您在它的末尾添加一个
。\u一个
,它实际上会运行。啊哈。这样做了,现在数字更准确了=)比较:第一:986.6 i/s查找:940.7 i/s-相同的ish:差异在错误范围内,其中:931.6 i/s-相同的ish:差异在错误范围内AHHH。比较:第一:986.6 i/s查找:940.7 i/s-相同的ish:差异在错误范围内,其中:931.6 i/s-相同的ish:差异在错误范围内