This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Allow PADTMPs’ strings to be swiped
authorFather Chrysostomos <sprout@cpan.org>
Thu, 14 Nov 2013 02:10:49 +0000 (18:10 -0800)
committerFather Chrysostomos <sprout@cpan.org>
Sat, 30 Nov 2013 13:53:16 +0000 (05:53 -0800)
commit9ffd39ab75dd662df22fcdafbf7f740838acc898
tree13e7c1cb4bdb8382b540c808db62eed312ada409
parent0fd5eacbba20c136307374df51bc994313db0157
Allow PADTMPs’ strings to be swiped

While copy-on-write does speed things up, it is not perfect.  Take
this snippet for example:

$a = "$b$c";
$a .= $d;

The concatenation operator on the rhs of the first line has its own
scalar that it reuses every time that operator is called (its target).
When the assignment happens, $a and that target share the same string
buffer, which is good, because we didn’t have to copy it.  But because
it is shared between two scalars, the concatenation on the second line
forces it to be copied.

While copy-on-write may be fast, string swiping surpasses it, because
it has no later bookkeeping overhead.  If we allow stealing targets’
strings, then $a = "$b$c" no longer causes $a to share the same string
buffer as the target; rather, $a steals that buffer and leaves the tar-
get undefined.  The result is that neither ‘$a =’ nor ‘$a .= $d’ needs
to copy any strings.  Only the "$b$c" will copy strings (unavoidably).

This commit only applies that to long strings, however.  This is why:

Simply swiping the string from any swipable TARG (which I tried at
first) resulted in a significant slowdown.  By swiping the string from
a TARG that is going to be reused (as opposed to a TEMP about to be
freed, which is where swipe was already happening), we force it to
allocate another string next time, greatly increasing the number
of malloc calls.  malloc overhead exceeds the overhead of copying
short strings.

I tried swiping TARGs for short strings only when the buffer on the
lhs was not big enough for a copy (or there wasn’t one), but simple
benchmarks with mktables show that even checking SvLEN(dstr) is enough
to slow things down, since the speed-up this provides is minimal where
short strings are involved.

Then I tried checking just the string length, and saw a consistent
speed increase.  So that’s what this patch uses.  Programs using short
strings will not benefit.  Programs using long strings may see a 1.5%
increase in speed, due to fewer string copies.
ext/Devel-Peek/t/Peek.t
pp_ctl.c
sv.c