【问题标题】:pluck vs distinct in mongoid db. which is faster?在 mongoid db 中采摘与不同。哪个更快?
【发布时间】:2016-05-19 20:12:27
【问题描述】:

看来mongodb有两个等价的方法:

#pluck#distinct 都只返回集合中的给定字段。

两者都是

User.pluck(:name)
User.distinct(:name)

将从数据库中的用户集合中返回所有名称的数组

> ['john', 'maria', 'tony', 'filip']

我不介意重复。哪种方法更快?

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    让我们运行一个基准测试!

    require 'benchmark'
    
    
    1_200.times { FactoryGirl.create(:user) }
    
    Benchmark.bmbm(7) do |bm|
      bm.report('pluck') do
        User.pluck(:email)
      end
    
      bm.report('pluck.uniq') do
        User.pluck(:email).uniq
      end
    
      bm.report('only.pluck') do
        User.only(:email).pluck(:email)
      end
    
      bm.report('only.pluck.uniq') do
        User.only(:email).pluck(:email).uniq
      end
    
      bm.report('distinct') do
        User.distinct(:email)
      end
    
      bm.report('only.distnct') do
        User.only(:email).distinct(:email)
      end
    end
    

    哪个输出:

    Rehearsal ------------------------------------------------
    pluck          0.010000   0.000000   0.010000 (  0.009913)
    pluck.uniq     0.010000   0.000000   0.010000 (  0.012156)
    only.pluck     0.000000   0.000000   0.000000 (  0.008731)
    distinct       0.000000   0.000000   0.000000 (  0.004830)
    only.distnct   0.000000   0.000000   0.000000 (  0.005048)
    --------------------------------------- total: 0.020000sec
    
                       user     system      total        real
    
    pluck          0.000000   0.000000   0.000000 (  0.007904)
    pluck.uniq     0.000000   0.000000   0.000000 (  0.008440)
    only.pluck     0.000000   0.000000   0.000000 (  0.008243)
    distinct       0.000000   0.000000   0.000000 (  0.004604)
    only.distnct   0.000000   0.000000   0.000000 (  0.004510)
    

    它清楚地表明使用#distinct 几乎是#pluck 的两倍

    【讨论】:

    • 我认为这是我在这里所做的低质量基准测试。不要在任何地方使用它作为最终参数。该基准测试缺少分析模式(无缓存?)并且正在处理更大的数据集
    猜你喜欢
    • 2020-06-15
    • 2010-10-09
    • 2014-12-04
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多