I'm working on a project where I use the cJSON library to handle JSON data. I have a scenario where I need to represent pairs of numeric values, and I'm trying to optimize the memory usage.
I have two different implementations for adding data to a cJSON array, and I'm wondering which one is more memory-efficient in terms of cJSON's internal representation.
void AddFOVToRender(int Radius) {
cJSON* FOVArray = cJSON_CreateArray();
cJSON_AddItemToArray(FOVArray, cJSON_CreateNumber(TYPE_FOV));
cJSON_AddItemToArray(FOVArray, cJSON_CreateNumber(Radius));
cJSON_AddItemToArray(jsonArray, FOVArray);
}
void AddFOVToRender(int Radius) {
int fovValues[2] = { TYPE_FOV, Radius };
cJSON_AddItemToArray(jsonArray, cJSON_CreateIntArray(fovValues, 2));
}
I'm asking this question because I'll be sending large amounts of data of shared memory and with it being rendered on my screen, it needs to fast as possible and also being a small data size since ill be rendering alot of objects at once.
I'm interested in understanding which approach is more memory-efficient in cJSON. I've reviewed cJSON's documentation, but I couldn't find specific details on the internal representation or potential memory optimizations for such scenarios.
I reckon you need to suck it and see.
There are a lot of assumptions to clear up for a theoretical approach to be useful. For example, I don't know whether FOV is an integer or a float, what range it will take or how many decimal places it will end up being allocated inside the object due to precision issues (I've seen floats like 1.3 end up being represented as a double like 1.300000234 in cJSON. Your best bet is to generate a small piece of code which does nothing except generate the packets as you intend and take a look at the heap size in each case.
One additional suggestion is to generate your 2 objects, and then simply do something like this:
This obviously won't account for the internal type sizes etc in the cJSON object, but should be a good enough benchmark to highlight whether one option is significantly better than the other.