Performance: avoid cloning when saving document if `minimize: false`
Prerequisites
- [x] I have written a descriptive issue title
- [x] I have searched existing issues to ensure the issue has not already been raised
Issue
In $__handleSave() we have the following:
if (this.$isNew) {
// send entire doc
const obj = this.toObject(saveToObjectOptions);
However, if minimize: false, we don't need to run toObject(), we can just do const obj = this._doc because the MongoDB driver will clone and apply toBSON() anyway. This should significantly help performance.
Re: #8024, let's implement this functionality first and make sure it works as intended before considering making minimize default to false.
We did some digging and this doesn't help as much as we originally thought. BSON serialization calls toBSON() which calls toObject() anyway. So this saves cloning the top level document props, but any arrays or subdocs still get toObject() treatment. In order to get substantial benefit we would need to store subdocs as POJOs in _doc, which is a more substantial undertaking.
Will defer this project for later
Hi @vkarpov15, I’m interested in contributing to this issue. I understand that it’s currently deferred, but I’d love to explore the cloning optimization when minimize: false and evaluate possible improvements around subdocument handling or BSON serialization behavior.
If you’re open to it, could I start experimenting with this locally and share a potential approach or draft PR for feedback?
Sure, try it out!