How to solve fragmentation of stringBuilder?

I get a beautiful SystemOutOfMemory exception in my StringBuilders. This is not due to the lack of a ram, so I believe that this is a fragmentation of memory.

I have ~ 200 StringBuiler objects. All of them are reused (using strBldr.clear ()). This seems to make my system fragment memory quite badly. How can i solve this?

Thanks:)

EDIT:

Here are some details:

Maximum registered input size & stringBuilder: 4,146,698.

Restarting restartable string files / seconds:> 120 (possibly → 120)

Input length @ first error: 16 972 (string)

StringBuilder length @ first error: 16

The number of times a new stringBuilder @ was created @ first error: ~ 32500

General drum use @ first error 637 448K

+4
source share
3 answers

I agree, most likely, you do not have enough memory, but fragmentation.

You need to get acquainted with fragmentation and a bunch of large objects (LOH).

You do not provide any details, so I can give only very broad advice:

  • try to evaluate how large your lines are and use the Capacity parameter for the new SB
  • round (valid) these sizes to a few units. This promotes reuse.
  • use Clear () when you expect that the new content will be almost the same size as the old one, growing is what kills you.

Edit

Maximum registered input size & stringBuilder: 4,146,698.

  • Make sure no intermediate elements are needed with a large size, and then
  • Create all StringBuilders as sb1 = new StringBuilder(4200000);
  • Do not try to reuse them (too much / in general)
  • Do not hold them for too long.
+4
source

You should not reuse StringBuilder , just create a new one as needed.

When you call Clear on a StringBuilder , it will not free all used memory, but will only use reset the used size. It will still have the same large buffer, and reusing StringBuilder only means that the buffer will be as large as it ever was and never shrink.

Also, storing StringBuilder objects for reuse means that they save garbage collections and move on to the next generation heap. They are less likely to gather, which is why they are more likely to perceive memory fragmentation.

+4
source

As a result, I switched to x64 . This solved my problems.

It is possible that I always assigned the entire x86 memory space, although I did not use all of this. Porting to x64 will probably solve this problem.

0
source

All Articles