Skip to contentSkip to conversation

qobject/json-writer: preallocate output buffer

PATCH In review Bin Guo 2 participants 2 messages Jun 3

lore
Share & tools
lore

Bin Guo

author
#0 lore raw

PATCH v2 1/1 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.

---
v1->v2: drop "one page" argument from commit message and comment
(per Markus Armbruster's review)

 qobject/json-writer.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
qobject/json-writer.c +4 -1
index aac2c6ab71..c23c81709b 100644
@@ -24,13 +24,16 @@ struct JSONWriter {
     GByteArray *container_is_array;
 };
 
+/* Should cover most QMP responses without reallocation */
+#define JSON_WRITER_INITIAL_SIZE  4096
+
 JSONWriter *json_writer_new(bool pretty)
 {
     JSONWriter *writer = g_new(JSONWriter, 1);
 
     writer->pretty = pretty;
     writer->need_comma = false;
-    writer->contents = g_string_new(NULL);
+    writer->contents = g_string_sized_new(JSON_WRITER_INITIAL_SIZE);
     writer->container_is_array = g_byte_array_new();
     return writer;
 }
Signature · 1 line
2.50.1 (Apple Git-155)
#1 lore raw
Quoted 5 lines · Bin Guo

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.

Quoted 7 lines

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.

Thanks!

Paolo, perhaps you can merge this together with your JSON parser patches.