I'm writing an application that, when the user requests something, I prepare some output for them, and return it to them.

I wrote (or rather, adapted an existing) server skeleton, which accepts new connections, and creates input and output buffers for each new connection. Currently the output buffer for each user is a single string.

In my server, I get the users input, and send it on to another file to prepare the appropriate output. That file generates the output and returns it to the server, which places it in the outgoing buffer. All pretty standard, right?

So my question: the output for each request is generated in chunks, sometimes as large as a few kilos per chunk. Each request tends to have at least 2 chunks generated, and as many as 5. Currently, to add the new chunk to the existing output, I do

$outBuffer .= $newChunk

Is this copying of strings incredibly inefficient, as it seems to me that it might be? Would I be better off pushing each chunk of output onto an outgoing array. I assume that an array would be more memory inefficient, but speed is more important. Are there other issues/solutions I haven't thought of?

(It's a pretty significant change to my program, so I tried running the benchmark module on a small example I contrived. Alas, my company doesn't have perl configured correctly to run a lot of modules, benchmark being one of those)


In reply to append to a string or make an array? (memory and time efficiency) by swkronenfeld

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.