Commit eb3a828864 for perl
commit eb3a828864ee663356199c2723f8b8566fddb473
Author: Richard Leach <rich+perl@hyphen-dash-hyphen.info>
Date: Wed Nov 4 17:14:10 2026 +0000
pp_subst: size a new dstr to fit (once) or match the source size
This replaces the strategy of creating a new `dstr` buffer from the
match prefix (if there was one) and growing it as necessary.
Previously, if the final buffer size turned out to be:
* close to that prefix size, no over-allocation occurred. (Best case.)
* closer to the source size and much larger than the prefix, then
multiple Renew() calls would be required AND the final allocation
could be larger than the size of the source buffer.
* larger than the source size - same as above.
A notable worse-case observed in _configpm_ (not sure of the source
code behind it):
5093 byte source buffer length
20 realloc calls
4526 byte final content length
5384 byte final buffer length
With this commit:
* For one-shot, simple substitutions, the buffer is accurately sized.
* For everything else, the new buffer is sized to match the source
and shrunk at the end if necessary.
diff --git a/pp_hot.c b/pp_hot.c
index 9151ee1f3b..1a75b63848 100644
--- a/pp_hot.c
+++ b/pp_hot.c
@@ -5403,7 +5403,7 @@ PP(pp_subst)
char *s;
char *strend;
const char *c;
- STRLEN clen;
+ STRLEN clen = 0;
SSize_t iters = 0;
SSize_t maxiters;
U8 rxtainted = 0; /* holds various SUBST_TAINT_* flag bits.
@@ -5687,8 +5687,26 @@ PP(pp_subst)
rxtainted |= SUBST_TAINT_PAT;
repl = dstr;
s = RXp_OFFS_START(prog,0) + orig;
- dstr = newSVpvn_flags(orig, s-orig,
- SVs_TEMP | (DO_UTF8(TARG) ? SVf_UTF8 : 0));
+
+ dstr = sv_2mortal(newSV(
+ (once && c && cBOOL(DO_UTF8(TARG) == doutf8))
+ /* We can exactly size this buffer */
+ ? len - (RXp_OFFS_END(prog,0) - RXp_OFFS_START(prog,0))
+ + clen + 1 /* +1 for COW byte */
+
+ /* Final buffer size is unknowable. For a /g substitution,
+ * it seems better to initially match size with the source
+ * and shrink at the end, rather than start small but
+ * potentially incur multiple calls to Renew() - which
+ * could result in an unnecessarily large final allocation
+ * that is either wasteful or has to be shrunk. */
+ : len + clen + 1 /* +1 for COW byte */
+ ));
+ SvCUR_set(dstr, s-orig);
+ *SvEND(dstr) = '\0';
+ SvFLAGS(dstr) |= SVf_POK|SVp_POK|(DO_UTF8(TARG) ? SVf_UTF8 : 0);
+ Copy(orig, SvPVX(dstr), s-orig, char);
+
if (!c) {
/* not known replacement string - call out to ops and OP_SUBSTCONT */
PERL_CONTEXT *cx;
@@ -5741,6 +5759,8 @@ PP(pp_subst)
assert(strend >= s);
sv_catpvn_nomg_maybeutf8(dstr, s, strend - s, DO_UTF8(TARG));
+ SvPV_shrink_to_cur(dstr);
+
if (rpm->op_pmflags & PMf_NONDESTRUCT) {
/* From here on down we're using the copy, and leaving the original
untouched. */