How much is it going to cost me (in CPU use) to count the "\n" characters in a string?

I'm getting the string by sysread on a socket into a buffer (not necessarily empty when I start). Somebody else is consuming off the front of the buffer, writing it out another port, so I need to get the line count for the bit I've just read and add that to my running total before I exit.

I'm thinking in terms of looping, using substr, to examine each character; vs. doing something with regexps (it's obvious how to find the first \n in the range, and I can use the length of the match string to tell me where to start searching for the next); vs. using unpack or something to make an array, and grep to find the newlines, and get the count by calling it in a string context.

All of these are sounding a little like too much work to justify for adding a line count to the logging. At the very least, I should check the log level before doing the work. Anyway, I'm wondering how noticeable it'll be. I guess it's just CPU time, which we're not short of (each proxied connection gets its own child process).


In reply to Char counting by dd-b

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.