Skip to content

Commit b14b1eb

Browse files
Teach convert() and friends to avoid copying when possible.
Presently, pg_convert() allocates a new bytea and copies the result regardless of whether any conversion actually happened. This commit adjusts this function to return the source pointer as-is if no conversion occurred. This optimization isn't expected to make a tremendous difference, but it still seems worthwhile to avoid unnecessary memory allocations. Author: Yurii Rashkovskii Reviewed-by: Bertrand Drouvot Discussion: https://postgr.es/m/CA%2BRLCQyknBPSWXRBQGOi6aYEcdQ9RpH9Kch4GjoeY8dQ3D%2Bvhw%40mail.gmail.com
1 parent e7c6efe commit b14b1eb

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/backend/utils/mb/mbutils.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -585,19 +585,19 @@ pg_convert(PG_FUNCTION_ARGS)
585585
src_encoding,
586586
dest_encoding);
587587

588-
/* update len if conversion actually happened */
589-
if (dest_str != src_str)
590-
len = strlen(dest_str);
588+
589+
/* return source string if no conversion happened */
590+
if (dest_str == src_str)
591+
PG_RETURN_BYTEA_P(string);
591592

592593
/*
593594
* build bytea data type structure.
594595
*/
596+
len = strlen(dest_str);
595597
retval = (bytea *) palloc(len + VARHDRSZ);
596598
SET_VARSIZE(retval, len + VARHDRSZ);
597599
memcpy(VARDATA(retval), dest_str, len);
598-
599-
if (dest_str != src_str)
600-
pfree(dest_str);
600+
pfree(dest_str);
601601

602602
/* free memory if allocated by the toaster */
603603
PG_FREE_IF_COPY(string, 0);

0 commit comments

Comments
 (0)