mongodb的set,inc,push比较

老实说,我并不是很清楚为什么这3个要放在一起比较,inc和set有相似的地方,push和这2个感觉完全不一样啊。

实验中用的是ruby的mongo_ruby_driver来写程序的,为了获得比较精确的数值,我使用了benchmark这个module,反复执行set,inc,push各3000次。代码如下

#!/usr/bin/env ruby
# 20140301, mongo_test.rb
###
# test inc, set, push
###


require "rubygems"
require "mongo"
require "benchmark"

class MongoConnection
  def initialize(host, port)
    @mongoconn = Mongo::MongoClient.new(host, port)
    @db = @mongoconn.db("test")
  end

  def test()
    @coll = @db.collection("test")

    # set test
    @coll.insert({"num"=>0})
    tm_start = Time.now.to_f
    # (1..3000).each { |i| @coll.update({ }, { "$set" => {"num"=>i} } ) }
    Benchmark.bm do |t|
      t.report{ (1..3000).each { |i| @coll.update({ }, { "$set" => {"num"=>i} } ) } }
    end
    # p @coll.find.to_a
    tm_used = Time.now.to_f - tm_start
    puts "set Time used(s): #{tm_used}"
    @coll.drop

    # inc test
    @coll.insert({"num"=>0})
    tm_start = Time.now.to_f
    # (1..3000).each { |i| @coll.update({ }, { "$inc" => {"num"=>1} } ) }
    Benchmark.bm do |t|
      t.report{ (1..3000).each { |i| @coll.update({ }, { "$inc" => {"num"=>1} } ) } }
    end
    # p @coll.find.to_a
    tm_used = Time.now.to_f - tm_start
    puts "inc Time used(s): #{tm_used}"
    @coll.drop

    # push test
    @coll.insert({"num"=>[0]})
    tm_start = Time.now.to_f
    # (1..3000).each { |i| @coll.update({ }, { "$push" => {"num"=>i} } ) }
    Benchmark.bm do |t|
      t.report{ (1..3000).each { |i| @coll.update({ }, { "$push" => {"num"=>i} } ) } }
    end
    # p @coll.find.to_a
    tm_used = Time.now.to_f - tm_start
    puts "push Time used(s): #{tm_used}"
    @coll.drop

  end

end

mongo_conn = MongoConnection.new("localhost", 27017)

mongo_conn.test()

测试结果如下

       user     system      total        real
   1.570000   0.130000   1.700000 (  2.180069)
set Time used(s): 2.1805129051208496
       user     system      total        real
   1.480000   0.140000   1.620000 (  2.059199)
inc Time used(s): 2.0596039295196533
       user     system      total        real
   1.850000   0.200000   2.050000 (  6.312153)
push Time used(s): 6.312557935714722

实际上,从反复执行的结果来看,set和inc基本是在同一个时间量级上,也不一定set就比inc快,也有相反的时候;而push的时间始终比较慢。这个跟rdbms的结果差异很大,rdbms的set和inc用的是update来实现,push用insert来实现,单个update语句产生的redo log要比insert多,所以一般update比insert要慢。但是,mongodb的结果与此相差很大,怀疑跟其存储引擎有关。

mongodb的set,inc,push比较,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。