I want to use rapidJSON
to build JSON files.
I've noticed there are (at least) 2 options to do so.
The first is using rapidJSON::Writer
directly :
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.String("hello");
...
The other is using rapidJSON::Document
:
Document d;
d.SetObject();
d.AddMember("hello", "world", d.GetAllocator());
...
Besides the obvious differences of ease of use on the Document
side and more type control on the Writer
size, are there any performance differences ? are both allocations the same ?
Document
is a data structure for storing JSON tree (aka DOM) in memory. Writer
is needed to stringify (dump/serialize) a Document
into JSON:
d.Accept(writer);
So, if your application only needs to write JSON, and it can apply Writer
easily, it is preferred over Document
. It is because Document
needs memory allocation and additional overheads.
However, Document
is more easily for parsing and modify JSON.
P.S. In the current version of RapidJSON, it is prefer to use writer.Key("hello")
instead of writer.String("hello")
for object keys.