java outOfMemoryError with stringbuilder

前端 未结 6 746
囚心锁ツ
囚心锁ツ 2020-12-15 12:44

I\'m getting a java outOfMemoryError when I call this method - i\'m using it in a loop to parse many large files in sequence. my guess is that result.toString()

6条回答
  •  爱一瞬间的悲伤
    2020-12-15 13:04

    If your files to be processed are all very large, say more than a few hundred MB, then you really should go with stream processing instead of this "loading all into memory" way, just as @erickson suggested.

    Otherwise, there are a few things you could try, all to reduce memory usage as much as possible:

    1. Try properly enlarge your heap size if not yet (when applicable).
    2. Give StringBuffer an initial size same as the lenght of the given String buffer. This should reduce the unnecessary memory usage while expanding the StringBuffer in the process. I assume it is only replacing certain words of the original string and should be more or less the same in length.
    3. If possible, maybe you could return the generated StringBuffer object instead. Calling its toString() only after you get rid of the original String object.

提交回复
热议问题