JSONValue::parseCopy() vs JSONValue::parse()

Hi,
I'd like to know more about the JSONValue::parse() function.

It is stated in the docs that when we cannot modify the c-string we should use JSONValue::parseCopy():

If you have a buffer of data containing a JSON object or array,
you pass it to one of the static parse() methods.
In this example, parseCopy() is used because a subscription handler data
must not be modified (it is const).
It's a static method, so you always use it like JSONValue::parseCopy(data).

In all other cases, I guess when the data buffer can be modified, should we call JSONValue::copy()?
Are there other things to consider when choosing one over the other?

Thanks,
Gustavo.

1 Like

The parse() function breaks the string into tokens, and does so by writing null bytes to mark the end of the tokens. It does this in place to avoid having to allocate memory for each token in the JSON, of which there will be many.

Since it modifies the buffer you pass into parse(), there’s the other variation parseCopy() that makes a copy of the entire string first. This is necessary when the original can’t be modified, or you need to preserve the original string contents to use them again later.

If you don’t need the original buffer again and it can be modified, using parse() save a memory allocation the size of the input and a memory copy operation.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.