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



Background

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

关于我的测试

我已经用 200 个 mongoid 模型创建了 2k 记录。我在 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 集合比字符串集合小约 30%,因为 BSON objectID 可以充分利用索引前缀压缩。索引大小差异太小,无法看到 200 000 个文档的实际性能变化,但我想增加文档数量可能会显示不同的结果

最新更新