Append to string without copy?

Posted on
  • If I have a long string (say 2KB) is there a way to append to it without causing a second copy of the string to be made? E.g., does str += "more text" cause me to temporarily hold two copies in memory?

  • I'm pretty sure that str += "more text" will do a proper append automatically as-is, so it should be pretty fast.

    If you're interested the code is here

    It won't work if the string is referenced elsewhere though:

    var str = "Hello ";
    var foo = str;
    str += "more text"; // It's done a copy in this case.
    
  • ...that would be visible in the implementation of +=... This though would mean that the interpreter would know the number of references to the string at the time of concatenation and make the copy if there are more than one references... It all depends how assignments and garbage collect work...

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Append to string without copy?

Posted by Avatar for tve @tve

Actions