@samitouri / QOSamiQemu / commits / a21232a255

qobject/json-writer: preallocate output buffer

json_writer_new() creates the output GString with g_string_new(NULL), which starts at the GLib default of 64 bytes. Serializing typical QMP responses then requires multiple reallocations as the buffer grows -- for query-qmp-schema the GString is reallocated 12+ times. Preallocate JSON_WRITER_INITIAL_SIZE (4096) bytes. This covers most QMP responses without any reallocation. The JSONWriter is a short-lived object so the preallocation does not accumulate. Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org> Reviewed-by: Markus Armbruster <armbru@redhat.com> Signed-off-by: Bin Guo <guobin@linux.alibaba.com> Message-ID: <20260603022538.92780-1-guobin@linux.alibaba.com> Signed-off-by: Markus Armbruster <armbru@redhat.com>

Bin Guo committed Jun 3, 2026 at 10:25 UTC a21232a2558e947e5f9d46de9b9590d8e006050b
1 file changed +4 -1
qobject/json-writer.c
+4 -1
@@ -24,13 +24,16 @@ struct JSONWriter {
24 GByteArray *container_is_array;
25 };
26
27 +/* Should cover most QMP responses without reallocation */
28 +#define JSON_WRITER_INITIAL_SIZE 4096
29 +
30 JSONWriter *json_writer_new(bool pretty)
31 {
32 JSONWriter *writer = g_new(JSONWriter, 1);
33
34 writer->pretty = pretty;
35 writer->need_comma = false;
33 - writer->contents = g_string_new(NULL);
36 + writer->contents = g_string_sized_new(JSON_WRITER_INITIAL_SIZE);
37 writer->container_is_array = g_byte_array_new();
38 return writer;
39 }