To clean up unused space, you start an iterator at the root of the document and recursively write to a new buffer. This will clean up all the unused space. This operation can be delayed by the application for as long as they wish, until the size trade-off outweighs the cost of rebuilding.