Implement "max waste" thresholds to avoid problems with COW and deliberately overallo...
authorYves Orton <demerphq@gmail.com>
Sun, 11 May 2014 10:37:33 +0000 (12:37 +0200)
committerYves Orton <demerphq@gmail.com>
Mon, 12 May 2014 06:51:10 +0000 (08:51 +0200)
commite8c6a474e88610b73e62a19256dc8706b42f42b9
treeb01492b49e5f9ce6be96390d31d7dc6c1ba091fe
parentc8180b0692cef05079a2e250b3faccaca4592b10
Implement "max waste" thresholds to avoid problems with COW and deliberately overallocated pvs

COW does not play nicely with "preallocate" algorithms.

More specifically code like sv_gets() wants to preallocate a large
buffer into $_ for performance reasons.

Prior to COW this was just fine. When someone assigned $_ to a
less volatile variable only the used portion of the buffer was copied,
and the extended buffer would be reused by sv_gets() and all was well.

With COW however this process is foiled. The preallocated buffer
get shared, and then when $_ is updated the buffer is dropped from $_,
leaving the other SV holding ownership of the overallocated buffer,
and causing sv_gets() to allocate a new buffer entirely. This process
would then repeat consuming time and lots of memory.

This patch introduces a "wastage" check to COW. When decided if we
should COW a string we look at the ratio and difference of SvCUR(sv)
and SvLEN(sv), which represent the "actual string length" and the
"allocated string length". When the difference exceeds a hard threshold,
or when the ration exceeds a designated factor then we do not COW.

This means that strings with large overallocations are not COWed.
Exactly how this works out in practice, where SvGROW() *always*
overallocates, is an open question.

See: https://rt.perl.org/Ticket/Display.html?id=121796

This patch also slightly tweaks SvGROW() not to do roundup on the first
allocation of the pv. Odds are good that the initial request realy does
want exactly what they expected. (SvGROW contrary to what the name
suggests is used for bother *extended* the size of a pv, and
initializing it the first time.)
sv.c
sv.h