Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - StringBuilder for string concatenation throws OutOfMemoryException

We mostly tend to following the above best practice.

Have a look at String vs StringBuilder

But StringBuilder could throw OutOfMemoryException even when there is sufficient memory available. It throws OOM exception because it needs "continuous block of memory".

Some links for reference StringBuilder OutOfMemoryException

and there are many more.....

How many of you faced this problem or aware and what did you do to resolve it?

Is there anything I am missing?

P.S: I wasn't aware of this.

I have rephrased the question.

*** The same thing worked with manual concatenation(I'll verify this and update SO). The other thing that caused me concern was that there is enough memory in the system. That's the reason I raised this question here to check whether any one faced this problem or there was something drastically wrong with the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...