StringBuilder的字符串连接抛出OutOfMemoryException异常 [英] StringBuilder for string concatenation throws OutOfMemoryException

查看:684
本文介绍了StringBuilder的字符串连接抛出OutOfMemoryException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们大多倾向于按照上面的最佳实践。

We mostly tend to following the above best practice.

看一看字符串VS StringBuilder的

但StringBuilder的可能抛出的 OutOfMemoryException异常,即使有足够的可用内存。它抛出OOM异常,因为它需要连续的存储器块。

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

参考某些链接
的StringBuilder OutOfMemoryException异常

和还有更多......

and there are many more.....

你们有多少人面对这个问题,或者知道和你做了什么来解决?

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

有什么我失踪?

P.S:我当时没有意识到这一点

我已经改写了问题。

***与手动串联工作同样的事情(我会验证这一点,并更新SO)。引起我关注的另一件事是,有足够的内存在系统中。这就是我在这里提出这个问题,检查是否任何一个面对这个问题,或者有什么显着错误的code中的原因。

*** 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.

推荐答案

您创建的underyling字符串还需要一个连续的内存块,因为它重新psented作为字符数组$ P $(阵列需要连续内存)。如果StringBuilder的抛出OOM异常,你woludn't能够建立底层离不开它。

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.

如果创建一个字符串导致OOM,有可能是在你的应用更严重的问题。

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

编辑回应澄清:

有情况下,当手动拼接成功建立一个字符串一个StringBuilder将失败的一小部分。手动拼接将使用以两个字符串结合起来,而一个StringBuilder已分配内存不同algorithmn所需的精确长度。这是更积极,将可能分配比实际需要的字符串更多的内存。

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.

使用一个StringBuilder也将导致因为字符串将在以System.String形式present和StringBuilder同时很短的时间需要对内存进行临时增加一倍。

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.

但是,如果一个方法是使一个OOM,另一个是不,它仍可能指向在程序的更严重的问题。

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.

这篇关于StringBuilder的字符串连接抛出OutOfMemoryException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆