StringBuilder for string concatenation throws OutOfMemoryException

后端 未结 8 1654
南旧
南旧 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:54

    The underyling string you create will also need a contiguous block of memory because it is represented as an array of chars (arrays require contiguous memory) . If the StringBuilder throws an OOM exception you woludn't be able to build the underlying without it.

    If creating a string causes an OOM, there is likely a more serious issue in your application.

    Edit in response to clarification:

    There is a small subset of cases where building a string with a StringBuilder will fail when manual concatenation succeeds. Manual concatenation will use the exact length required in order to combine two strings while a StringBuilder has a different algorithmn for allocating memory. It's more aggressive and will likely allocate more memory than is actually needed for the string.

    Using a StringBuilder will also result in a temporary doubling of the memory required since the string will be present in a System.String form and StringBuilder simultaneously for a short time.

    But if one way is causing an OOM and the other is not, it still likely points to a more serious issue in your program.

提交回复
热议问题