What is the best approach when attempting to construct JSON string repeatedly in every cycle of main loop in case one wants to avoid memory allocation in every cycle? Could formatted string be somehow directly stored in pre-allocated bytearray?
The JSON string always contains same keys, but lenght(number of digits) of values may vary in every cycle.
JSON string vs bytearray
Re: JSON string vs bytearray
If you know the maximum number of digits, then you could allocate that in the JSON array. You could use a memoryview to map directly to those bytes. When you format the numbers use leading spaces but always make them the length of your max number, for example:
If you really want to reduce memory allocation you should write your own integer to string conversion routine, although that may not be required since we're only talking about a small allocation now.
EDIT: If you put unique numbers/ids in for each place that you want a number, you can use str.find to get the index for creating the memory view.
Code: Select all
>>> '{:6d}'.format(123)
' 123'
EDIT: If you put unique numbers/ids in for each place that you want a number, you can use str.find to get the index for creating the memory view.