性能 - Mongo 的 ID:BSON 或字符串

Performance - ID for Mongo: BSON or String

背景

我正在做一些测试,看看哪个最适合作为主键。我认为 BSON 会比字符串更好。但是,当我 运行 进行一些测试时,我得到了大致相同的结果。我是不是做错了什么,或者有人可以确认这是正确的吗?

关于我的测试

我已经用 2 个 mongoid 模型创建了 200k 条记录。我 运行 ruby 基准测试中的所有内容。我做了三个主要查询,一个 find(id) 查询,一个 where(id: id) 查询和一个 where(:id.in => array_of_ids)。所有这些都给了我非常相似的响应时间。

Benchmark.bm(10) do |x|
  x.report("String performance")  { 100.times { ModelString.where(id: '58205ae41d41c81c5a0289e5').pluck(:id) } }
  x.report("BSON performance")    { 100.times { ModelBson.where(id: '581a1d271d41c82fc3030a34').pluck(:id) } }
end

这是我在 Mongoid 中的模型:

class ModelBson
  include Mongoid::Document
 
end

class ModelString
  include Mongoid::Document
  field :_id, type: String, pre_processed: true, default: ->{ BSON::ObjectId.new.to_s }
end

基准测试结果

ID miss "find" query
                 user     system      total        real
String performance  0.140000   0.070000   0.210000 (  2.187263)
BSON performance  0.280000   0.060000   0.340000 (  2.308928)

ID hit "find" query
                 user     system      total        real
String performance  0.280000   0.060000   0.340000 (  2.392995)
BSON performance  0.190000   0.060000   0.250000 (  2.245230)

100 IDs "in" query hit
String performance 0.850000   0.110000   0.960000 (  9.221822)
BSON performance  0.770000   0.060000   0.830000 (  8.055971)

db.collection.stats

{
        "ns" : "model_bsons",
        "count" : 199221,
        "size" : 9562704,
        "avgObjSize" : 48,
        "numExtents" : 7,
        "storageSize" : 22507520,
        "lastExtentSize" : 11325440,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 1,
        "capped" : false,
        "nindexes" : 1,
        "indexDetails" : {

        },
        "totalIndexSize" : 6475392,
        "indexSizes" : {
                "_id_" : 6475392
        },
        "ok" : 1
}


{
        "ns" : "model_strings",
        "count" : 197680,
        "size" : 9488736,
        "avgObjSize" : 48,
        "numExtents" : 7,
        "storageSize" : 22507520,
        "lastExtentSize" : 11325440,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 1,
        "capped" : false,
        "nindexes" : 1,
        "indexDetails" : {

        },
        "totalIndexSize" : 9304288,
        "indexSizes" : {
                "_id_" : 9304288
        },
        "ok" : 1
}

这是正确的。

正如您从集合统计信息中看到的那样,两个集合中的文档具有相同的大小(avgObjSize 字段)。所以 BSON ObjectID 和字符串字段大小(都是 12 字节)没有区别。

真正重要的是索引大小。在这里你可以注意到索引大小 BSON 集合比 String 集合小 30% 左右,因为 BSON objectID 可以充分利用 index prefix compression。索引大小差异太小,看不到 200 000 个文档的实际性能变化,但我想增加文档数量可能会显示不同的结果