StringBuilder for string concatenation throws OutOfMemoryException

后端 未结 8 1667
南旧
南旧 2020-12-06 10:13

We mostly tend to following the above best practice.

Have a look at String vs StringBuilder

But StringBuilder could throw OutOfMemoryException even w

相关标签:
8条回答
  • 2020-12-06 10:57

    I had a very similar experience where I was appending strings but forgot to add the String.Format. Thus:

    myStringBuilder.Append("1,""{0}""", someVeryLargeIntVariable)
    

    should have been:

    myStringBuilder.Append(String.Format("1,""{0}""", someVeryLargeIntVariable))
    

    Note that this is my vb.net code that failed. I replicated a similar test in c# with:

    myStringBuilder.Append('a', 1564544656);
    

    vs.

    myStringBuilder.Append(string.Format("1,\"{0}\"", 1564544656));
    

    But in my case, vb.net got me in trouble b/c of the implicit conversions (I couldn't parallel the exact same problem in c#).

    I hope that helps someone.

    0 讨论(0)
  • 2020-12-06 11:01

    If you look at how StringBuilder is implemented, you'll see that it actually uses a String to hold the data (String has internal methods, that will allow StringBuilder to modify in place).

    I.e. they both use the same amount of memory. However, since StringBuilder will automatically extend the underlying array and copy as necessary when needed (but doubling the capacity) that is most likely the cause of the out of memory error. But as others have already pointed out both of the require a continuous block of memory,

    0 讨论(0)
提交回复
热议问题