What is StringBuilder's RAM consumption like?

后端 未结 5 782
广开言路
广开言路 2021-01-12 15:39

We have a few operations where we are doing a large number of large string concatenations, and have recently encountered an out of memory exception. Unfortunately, debuggin

5条回答
  •  被撕碎了的回忆
    2021-01-12 16:11

    Strigbuilder is a perfectly good solution to memory problems caused by concatenating strings.

    To answer your specific question, Stringbuilder has a constant-sized overhead compared to a normal string where the length of the string is equal to the length of the currently-allocated Stringbuilder buffer. The buffer could potentially be twice the size of the string that results, but no more memory allocations will be made when concatenating to the Stringbuilder until the buffer is filled, so it is really an excellent solution.

    Compared with string, this is outstanding.

    string output = "Test";
    output += ", printed on " + datePrinted.ToString();
    output += ", verified by " + verificationName;
    output += ", number lines: " + numberLines.ToString();
    

    This code has four strings that stored as literals in the code, two that are created in the methods and one from a variable, but it uses six separate intermediate strings which get longer and longer. If this pattern is continued, it will increase memory usage at an exponential rate until the GC kicks in to clean it up.

提交回复
热议问题