在mongoengine的官方文档中,它说从0.8开始,no_cache()被添加到mongoengine中。它能给我们带来什么好处?no_cache申请的典型场景是什么?
发布于 2019-06-05 03:41:53
Mongoengine maintainer here -默认情况下(以及历史上),当你在查询集上迭代时,mongoengine会缓存所有结果。这样做的好处是,如果您重新迭代相同的变量,则不会触发查询,但缺点是将所有内容都保存在内存中。即:
class User(Document):
pass
users = User.objects() # users is a queryset, it didn't hit the db yet
_ = [us for us in in users] # hits the db and caches all user instances in the users object
_ = [us for us in in users] # does not hit the db anymore, uses the users cached data
users = User.objects().no_cache()
_ = [us for us in in users] # hits the db and caches all user instances
_ = [us for us in in users] # hits the db again
使用缓存听起来像是一个好主意,但在实践中,您很少对同一查询集迭代两次,如果您正在迭代非常大的集合,那么内存消耗可能会成为一个问题。
请注意,将来可能会更改为默认使用no_cache
版本
https://stackoverflow.com/questions/53588542
复制相似问题