On 25/11/2026 16:30, Tom Lane wrote: > A side point is that I think you don't need to switch in and out > of the temp context each time through the loop. Once the StringInfo > buffer is created it'll repalloc itself bigger in its original > context, and there's nothing saying you can't reset the current > context. This probably wouldn't be worth worrying about in itself, > but it might make it less messy to implement the first idea.
Makes total sense.. thank you for clarifying! Done that way in 0001 and 0002. > On Wed, 25 Nov 2026 at 22:43, Tom Lane <[email protected]> wrote: >> I did this simple test: >> >> \timing on >> do $$ >> declare arr text[] default array_fill(''::text, ARRAY[50]); >> begin >> for i in 1..1000000 loop >> perform xmlelement(name a, arr); >> end loop; >> end$$; >> >> With HEAD this takes about 6400ms for me, with the patch >> about 6700ms. (These numbers are in an assert-enabled >> build, so take them with a grain of salt.) That seems >> like it's not really enough of a hit to justify contorting >> the code, so consider this objection withdrawn. I tested this query with v3-0001 in a -O2 build without --enable-cassert and I see no slowdown: master: n=19 min=6150.3 ms max=6617.7 ms avg=6254.1 ms patched: n=19 min=6073.2 ms max=6188.7 ms avg=6117.0 ms >> Another thing I noticed is that we are doing the type-output >> function lookup over again for each array element, though >> with some refactoring we could do it just once. Since that >> lookup is skipped for "bool" elements, I compared >> >> regression=# select length(xmlelement(name a, array_fill(true, >> ARRAY[16000000]))::text); >> length >> ----------- >> 368000007 >> (1 row) >> >> Time: 1196.610 ms (00:01.197) >> regression=# select length(xmlelement(name a, array_fill(''::text, >> ARRAY[16000000]))::text); >> length >> ----------- >> 304000007 >> (1 row) >> >> Time: 2005.366 ms (00:02.005) >> >> Now the time taken by textout is not zero, but it still looks like >> close to 50% of the runtime is going into those repeat lookups. >> Maybe that's enough to worry about? >> +1 I will take a look at this today or tomorrow and post a separate 0003 patch. On 25/11/2026 18:58, Kirill Reshke wrote: >>From my testing, it also turns out impact is measurable. > I used the following setup: > > CREATE TEMP TABLE xml_perf (v integer[]); > INSERT INTO xml_perf > SELECT ARRAY(SELECT g FROM generate_series(1, 8192) AS g); > ANALYZE xml_perf; > > query: > SELECT xmlelement(name r, v) > FROM xml_perf CROSS JOIN generate_series(1, 182); > > results, 15 runs: > > median min max > master 150.19 148.69 153.77 > + v2-0001 223.98 221.27 226.66 I was unable to reproduce these results with v3-0001 (now containing Tom's suggestions). I tried your query and got these results: master: n=19 min=155.6 ms max=161.9 ms avg=158.8 ms patched: n=19 min=152.9 ms max=162.1 ms avg=156.9 ms Also with -O2 and without --enable-assert. Can you share how your server was built? Thanks! Best, Jim
From 9830c13742e7584660e61d1ecb70236e063919d5 Mon Sep 17 00:00:00 2001 From: Jim Jones <[email protected]> Date: Thu, 26 Nov 2026 10:09:23 +0100 Subject: [PATCH v3 1/2] Fix memory growth when mapping arrays to XML map_sql_value_to_xml_value() converts each array element in the caller's memory context, so the intermediate data produced for every element accumulates until the end of the statement. For large arrays this can use far more memory than the result itself. The loop also does not check for interrupts. Convert each element in a temporary memory context that is reset after every iteration, and add CHECK_FOR_INTERRUPTS() to the loop. Author: Jim Jones <[email protected]> Reviewed-by: Jakub Wartak <[email protected]> Reviewed-by: Daniel Gustafsson <[email protected]> Reviewed-by: Tom Lane <[email protected]> Reviewed-by: Kirill Reshke <[email protected]> --- src/backend/utils/adt/xml.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c index 44a3a21d135..80a8e4c54d0 100644 --- a/src/backend/utils/adt/xml.c +++ b/src/backend/utils/adt/xml.c @@ -99,6 +99,7 @@ #include "utils/date.h" #include "utils/datetime.h" #include "utils/lsyscache.h" +#include "utils/memutils.h" #include "utils/rel.h" #include "utils/syscache.h" #include "utils/xml.h" @@ -2543,6 +2544,8 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings) Datum *elem_values; bool *elem_nulls; StringInfoData buf; + MemoryContext elemcxt; + MemoryContext oldcxt; int i; array = DatumGetArrayTypeP(value); @@ -2556,8 +2559,16 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings) initStringInfo(&buf); + /* Free per-element garbage, which can be large, after each element */ + elemcxt = AllocSetContextCreate(CurrentMemoryContext, + "map_sql_value_to_xml_value temporary cxt", + ALLOCSET_DEFAULT_SIZES); + oldcxt = MemoryContextSwitchTo(elemcxt); + for (i = 0; i < num_elems; i++) { + CHECK_FOR_INTERRUPTS(); + if (elem_nulls[i]) continue; appendStringInfoString(&buf, "<element>"); @@ -2565,8 +2576,12 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings) map_sql_value_to_xml_value(elem_values[i], elmtype, true)); appendStringInfoString(&buf, "</element>"); + + MemoryContextReset(elemcxt); } + MemoryContextSwitchTo(oldcxt); + MemoryContextDelete(elemcxt); pfree(elem_values); pfree(elem_nulls); -- 2.56.1
From 2a4ffc1ded47a508030f6ef098cf6da44b6f785a Mon Sep 17 00:00:00 2001 From: Jim Jones <[email protected]> Date: Wed, 25 Nov 2026 14:07:56 +0100 Subject: [PATCH v3 2/2] Fix memory growth in the *_to_xml() functions query_to_xml(), table_to_xml(), cursor_to_xml() and the functions built on them convert every row of the query result in the same memory context, so the intermediate data produced for each row accumulates until all rows have been processed. For large results this can use far more memory than the result itself. The row loop also does not check for interrupts. Convert each row in a temporary memory context that is reset after every iteration, and add CHECK_FOR_INTERRUPTS() to the loop. --- src/backend/utils/adt/xml.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c index 80a8e4c54d0..e19ab446e6d 100644 --- a/src/backend/utils/adt/xml.c +++ b/src/backend/utils/adt/xml.c @@ -2990,6 +2990,8 @@ cursor_to_xml(PG_FUNCTION_ARGS) StringInfoData result; Portal portal; + MemoryContext rowcxt; + MemoryContext oldcxt; uint64 i; initStringInfo(&result); @@ -3008,10 +3010,25 @@ cursor_to_xml(PG_FUNCTION_ARGS) errmsg("cursor \"%s\" does not exist", name))); SPI_cursor_fetch(portal, true, count); + + rowcxt = AllocSetContextCreate(CurrentMemoryContext, + "cursor_to_xml temporary cxt", + ALLOCSET_DEFAULT_SIZES); + oldcxt = MemoryContextSwitchTo(rowcxt); + for (i = 0; i < SPI_processed; i++) + { + CHECK_FOR_INTERRUPTS(); + SPI_sql_row_to_xmlelement(i, &result, NULL, nulls, tableforest, targetns, true); + MemoryContextReset(rowcxt); + } + + MemoryContextSwitchTo(oldcxt); + MemoryContextDelete(rowcxt); + SPI_finish(); if (!tableforest) @@ -3074,6 +3091,8 @@ query_to_xml_internal(const char *query, char *tablename, { StringInfo result; char *xmltn; + MemoryContext rowcxt; + MemoryContext oldcxt; uint64 i; if (tablename) @@ -3099,10 +3118,24 @@ query_to_xml_internal(const char *query, char *tablename, if (xmlschema) appendStringInfo(result, "%s\n\n", xmlschema); + rowcxt = AllocSetContextCreate(CurrentMemoryContext, + "query_to_xml_internal temporary cxt", + ALLOCSET_DEFAULT_SIZES); + oldcxt = MemoryContextSwitchTo(rowcxt); + for (i = 0; i < SPI_processed; i++) + { + CHECK_FOR_INTERRUPTS(); + SPI_sql_row_to_xmlelement(i, result, tablename, nulls, tableforest, targetns, top_level); + MemoryContextReset(rowcxt); + } + + MemoryContextSwitchTo(oldcxt); + MemoryContextDelete(rowcxt); + if (!tableforest) xmldata_root_element_end(result, xmltn); -- 2.56.1
