Hello, comrades monks!

I want to share knowledge about interesting regex behavior:

#!/usr/bin/env perl use strict; use warnings; use 5.022; # WARNING! Will consume about 3GB of RAM $| = 1; my $size = 1024 * 1024 * 1000; my $s = 'C' x $size; # eval << 'EOD'; $s =~ s/C/1/; # copy of CCCCC... will stay in memory $s =~ s/C/2/; # same but 1CCCC... # EOD print "Time to measure memory usage...\n"; sleep(9000);

Every expression with substitution call, will copy original string and store it until next call. So, memory not leaking and will be reused (for e.g. inside loop blocks), but this behavior can lead to serious RAM consumption. The only known (for me) workaround for this problem is string eval, that will force memory reclaim, but this is clumsy in my opinion.

What do you think about such behavior? Is there more elegant way to free up memory used by 's///'?

UPD:

Reproduced on 5.22.2 (Slackware 14.2), 5.30.0 (Centos 7), and no memory waste on 5.16.3 (Centos 7)

Investigation with 'Test::LeakTrace'

Interesting links:


In reply to Substitution with regex and memory consumption by k-mx

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.