如何解决stringBuilder碎片问题?
我在 StringBuilders 中遇到了一个很好的 SystemOutOfMemory 异常。这不是由于缺少内存,因此我认为这是内存碎片。
我有大约 200 个 StringBuiler 对象。所有这些都会定期重用(使用 strBldr.clear())。这似乎导致我的系统内存碎片非常严重。我该如何解决这个问题?
谢谢:)
编辑:
这里有一些数据:
输入的最大记录大小& stringBuilder: 4 146 698.
Avarage 重新启动 stringBuilders/秒: >120 (可能 >>120)
输入长度@第一个错误: 16 972 (字符串)
StringBuilder 长度@第一个错误: 16
新 stringBuilder 的次数已发生@第一个错误:~32500
总内存使用量@第一个错误 637 448K
I am getting a nice SystemOutOfMemory exception in my StringBuilders. It is not due to lack of ram, thus I believe it is memory fragmentation.
I have ~200 StringBuiler objects. All of these are reused regularly (with strBldr.clear()). This seems to cause my system to fragment the memory pretty bad. How can I solve this?
Thanks :)
EDIT:
Here are some data:
Max recorded size of input& stringBuilder: 4 146 698.
Avarage re-initiated stringBuilders/second: >120 (possibly >>120)
Length of input @ first error: 16 972 (string)
StringBuilder length @ first error: 16
Count of times a new stringBuilder had been made @ first error: ~32500
Total ram usage @ first error 637 448K
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意,很可能你没有耗尽内存,而是陷入碎片。
您必须熟悉碎片和大对象堆 (LOH)。
您没有提供任何详细信息,因此我只能提供一些非常广泛的建议:
编辑
sb1 = new StringBuilder(4200000);
I agree, most likely you are not running out of memory but into fragmentation.
You have to get acquainted with fragmentation and the Large Object heap (LOH).
You don't provide any details so I can only give some very broad advice:
Edit
sb1 = new StringBuilder(4200000);
您不应该像这样重复使用
StringBuilder
,只需根据需要创建一个新的。当您在
StringBuilder
上调用Clear
时,它不会释放它使用的所有内存,只会将已使用的大小重置为零。它仍然具有相同的大缓冲区,并且重复使用 StringBuilder 仅意味着缓冲区将达到所需的大小,并且永远不会缩小。此外,保留 StringBuilder 对象以供重用意味着它们可以通过垃圾回收并转移到下一代堆。这些收集的频率较低,因此它们更有可能对内存碎片敏感。
You should not reuse a
StringBuilder
like that, just create a new one as needed.When you call
Clear
on aStringBuilder
it will not release all the memory that it used, it will only reset the used size to zero. It will still have the same large buffer, and repeated use of theStringBuilder
only means that the buffer will be as large as it ever needed to be, and never shrink.Also, keeping the
StringBuilder
objects for reuse means that they survice garbage collections and move on to the next generation heap. Those are collected less frequently, so they are more likely to be sensetive to memory fragmentation.我最终做的是迁移到x64。这解决了我的问题。
有可能我准确地分配了 x86 的整个内存空间,尽管我没有全部使用它。迁移到 x64 肯定可以解决这个问题。
What I ended up doing is migrating to x64. This solved my problems.
It is possible that I accually assigned the entire memory space of x86, even though I did not use it all. Migrating to x64 certainly would solve that issue.