What's the best way to get the size in MB of Couchbase MutableDocument programmatically in kotlin

Hi everyone, I need help determining the size of a Couchbase MutableDocument in MB. Currently, I convert the document to JSON, then to a byte array, and calculate the size from there before converting it to MB. However, when the document is too large, I encounter an OutOfMemoryError. Any suggestions?

Increasing the JVM heap size could avoid the OutofMemoryError

I’m not at all surprised that trying to hold 4 complete copies of some documents, in memory, at the same time, causes an OOM. What does puzzle me is what you mean by “size of a MutableDocument”.

Maybe you want the size in native memory? The JSON is stored as a highly optimized binary representation called Fleece. The API does not provide any way of getting the size of the Fleece document.

Perhaps you are looking for the size in Java memory? That would be a bit difficult to compute but it is fairly small: only the portions of the document that you have explicitly referenced with the Java API are decompressed and copied into the Java heap. Of course, converting a doc to JSON copies ALL of them so you now have a complete compressed native copy of the doc and a complete uncompressed version in Java AND a JSON string. 3 complete copies, one compressed.

Maybe you want the size as represented on the network? It is the optimized Fleece representations of JSON that are sent over the network.

Finally, I definitely I don’t understand converting the JSON to a byte array. Why not just take the size of the JSON string?