I would like to process a lengthy (binary) string of length N as a stream, chopping off the front part as the parsing goes along.
my $n = unpack("v", $str); $str = substr($str, 1);
Now I have noted that my application considerably slows down on longer strings, and it seems that is due to the following effect, indicating that this approach scales as N^2 (instead of the naively expected N).
$ time perl -e '$a = "a" x 20_000; $a = substr($a, 1) while length($a) +;' user 0m0.350s $ time perl -e '$a = "a" x 40_000; $a = substr($a, 1) while length($a) +;' user 0m0.791s $ time perl -e '$a = "a" x 80_000; $a = substr($a, 1) while length($a) +;' user 0m2.683s
A similar issue was discussed in Access via substr refs 2000 times slower: I think the reason for this slowdown is that when constructing support for the lvalue property of substr, a copy is made. Is there a good workaround to this scaling issue? Instead of passing an ever-shrinking stream around different functions, I could just pass the whole string and an offset,
my $n = unpack("v", substr($str, $off, 2)); $off += 2;
but this seems rather clumsy to me... Are there more elegant ways of doing this?

Update: Thanks for all the help and for the insightful explanations! As suggested, the 4-argument version of substr (setting REPLACEMENT to "") instead of the (2|3)-argument substr solves this in a very neat manner,
my $n = unpack("v", substr($str, $off, 2, ""));

In reply to Using substr to split a string scales as N^2 -- alternatives? by hrr

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.