From 17a5871d9d58ea639b6d1ba4f0ce58462d55a33c Mon Sep 17 00:00:00 2001 From: David Rowley Date: Sat, 27 Jul 2024 23:46:07 +1200 Subject: Optimize escaping of JSON strings There were quite a few places where we either had a non-NUL-terminated string or a text Datum which we needed to call escape_json() on. Many of these places required that a temporary string was created due to the fact that escape_json() needs a NUL-terminated cstring. For text types, those first had to be converted to cstring before calling escape_json() on them. Here we introduce two new functions to make escaping JSON more optimal: escape_json_text() can be given a text Datum to append onto the given buffer. This is more optimal as it foregoes the need to convert the text Datum into a cstring. A temporary allocation is only required if the text Datum needs to be detoasted. escape_json_with_len() can be used when the length of the cstring is already known or the given string isn't NUL-terminated. Having this allows various places which were creating a temporary NUL-terminated string to just call escape_json_with_len() without any temporary memory allocations. Discussion: https://postgr.es/m/CAApHDvpLXwMZvbCKcdGfU9XQjGCDm7tFpRdTXuB9PVgpNUYfEQ@mail.gmail.com Reviewed-by: Melih Mutlu, Heikki Linnakangas --- src/backend/utils/adt/jsonb.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/backend/utils/adt/jsonb.c') diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c index e4562b3c6ce..928552d5514 100644 --- a/src/backend/utils/adt/jsonb.c +++ b/src/backend/utils/adt/jsonb.c @@ -354,7 +354,7 @@ jsonb_put_escaped_value(StringInfo out, JsonbValue *scalarVal) appendBinaryStringInfo(out, "null", 4); break; case jbvString: - escape_json(out, pnstrdup(scalarVal->val.string.val, scalarVal->val.string.len)); + escape_json_with_len(out, scalarVal->val.string.val, scalarVal->val.string.len); break; case jbvNumeric: appendStringInfoString(out, -- cgit v1.2.3