Written this way, you'll need roughly 6 bytes of memory for every character in the file.

Each character is two bytes. You have the raw input, the substituted output (in the buffer), and you are asking for a third copy when you run out of memory.

If the file is encoded in something like ASCII or ISO-8859-1 (a single-byte character encoding), that means it will be six times larger in memory than on disk.

You could allocate more memory to the process, but a better solution might be to process the input "streamwise"—read, scan, and write the data without loading it all into memory at once.

Answer from erickson on Stack Overflow
🌐
Coderanch
coderanch.com › t › 626258 › java › java-lang-OutOfMemoryError-Java-heap
java.lang.OutOfMemoryError: Java heap space using Stringbuilder (Java in General forum at Coderanch)
InputStream is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is,Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); In the readAll method i have written the code as below: private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } Iam getting an Out of memory exception at the line sb.append((char) cp); i need to get the string in order to pass to Json Object and similarly avoid this Memory issue.
Discussions

[BANano] [SOLVED] out of Memory heap ... at java.lang.StringBuilder.toString(StringBuilder.java:407)
Hi there Whilst I am able to solve this by adding: '#VirtualMachineArgs: -Xms1024m -Xmx1024m As per discussed in this article, https://www.b4x.com/android/forum/threads/parsing-huge-text-files.34923/ I'm just curious as to what could be the underlying cause. As it seems to be related to the... More on b4x.com
🌐 b4x.com
0
0
September 16, 2021
OutOfMemory errors caused by debug logging of incoming Kafka messages
We have seen OutOfMemoryErrors with the following stack trace. Analysis of heap dump showed a StringBuilder instance holding 275MB of memory that is a local variable in java.util.AbstractCollection... More on github.com
🌐 github.com
3
April 8, 2019
StringBuffer is dangerous when dealing with lonnnng Strings!!!
Java forum system / java discussion board More on captaincasademo.com
🌐 captaincasademo.com
November 22, 2011
Out of memory exception on Stringbuilder
Enshittification More on reddit.com
🌐 r/csharp
43
0
May 30, 2023
🌐
B4X
b4x.com › home › forums › b4j - desktop, server and raspberry pi › b4j questions
[BANano] [SOLVED] out of Memory heap ... at java.lang ...
September 16, 2021 - Hi there Whilst I am able to solve this by adding: '#VirtualMachineArgs: -Xms1024m -Xmx1024m As per discussed in this article, https://www.b4x.com/android/forum/threads/parsing-huge-text-files.34923/ I'm just curious as to what could be the underlying cause. As it seems to be related to the...
🌐
GitHub
github.com › odpi › egeria › issues › 860
OutOfMemory errors caused by debug logging of incoming Kafka messages · Issue #860 · odpi/egeria
April 8, 2019 - We have seen OutOfMemoryErrors with the following stack trace. Analysis of heap dump showed a StringBuilder instance holding 275MB of memory that is a local variable in java.util.AbstractCollection.toString(). java.lang.OutOfMemoryError:...
Author   odpi
🌐
Port135
port135.com › home › development › outofmemoryexception caused by stringbuilder
OutOfMemoryException caused by StringBuilder - port135.com
July 31, 2019 - The application is trying to assign with a very large set of data to a string When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.
🌐
Reddit
reddit.com › r/csharp › out of memory exception on stringbuilder
r/csharp on Reddit: Out of memory exception on Stringbuilder
May 30, 2023 -

Hi All, bit of a novice here.

I'm trying to extract xml from a large string which contains mixed characters (code below). So it contains #### and others so I can't simply loadxml I have to extract the specific xml. I can use indexof to extract a request and a response xml which is what I want, but when I read through the whole string I run out of memory on the line stringBuilder.AppendLine(text);

Can anyone tell if there is a better way to get what I want without excessive memory?

Thanks in advance for your help.

	public string AutoFormat(string result, string startTag)
	{
		string text;

		var stringBuilder = new StringBuilder();

		foreach (var index in result)
		{
			if (result.Contains($"<{startTag} ", StringComparison.OrdinalIgnoreCase) || result.Contains($"</{startTag}>", StringComparison.OrdinalIgnoreCase) || result.Contains(@$"<{startTag}Response xmlns=""http://www.tourenserver.de/""", StringComparison.OrdinalIgnoreCase) || result.Contains($"</{startTag}Response", StringComparison.OrdinalIgnoreCase))
			{
				int num = result.IndexOf($"<{startTag} ", StringComparison.OrdinalIgnoreCase);
				int num2 = result.IndexOf($"</{startTag}>", StringComparison.OrdinalIgnoreCase);
				int num1 = result.IndexOf(@$"<{startTag}Response xmlns=""http://www.tourenserver.de/""", StringComparison.OrdinalIgnoreCase);
				int num3 = result.IndexOf($"</{startTag}Response", StringComparison.OrdinalIgnoreCase);
				text = result.Substring(num, num2 - num + 7) + Environment.NewLine + Environment.NewLine + result.Substring(num1, num3 - num1 + 15);

				AddLine(stringBuilder, text);
			}
		}

		return stringBuilder.ToString();

		void AddLine(StringBuilder stringBuilder, string text)
		{
			stringBuilder.AppendLine(text);

		}
	}
Find elsewhere
🌐
B4X
b4x.com › home › forums › b4a - android › android questions
Out of memory with StringBuilder | B4X Programming Forum
September 3, 2020 - Any known memory limit with string builder? This happened while building a JSON string ~e:java.lang.OutOfMemoryError: Failed to allocate a 150994952 byte allocation with 25165824 free bytes and 72MB until OOM, max allowed footprint 150793064, growth limit 201326592 ~e: at java.util.Arrays.copyOf(Arrays.java:3260) ~e: at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:125)
🌐
Bug Database
bugs.java.com › bugdatabase › view_bug.do
Bug ID: JDK-4259569 StringBuffer.toString() can cause large memory usage
===Test Case========= //Test program: bug.java public class bug { // Allocate a large (1 Meg) static buffer that will be reused. static StringBuffer buffer = new StringBuffer(1024 * 1024); public static void main(String[] args) { final int limit = 100; int i; String[] s = new String[limit]; for (i=0; i < limit; i++) { // Clear buffer then add to it buffer.setLength(0); buffer.append(" "); // Create a string from the buffer and save it. s[i] = buffer.toString(); // Report progress System.out.println("Created String " + i); } } } Produces the following output: Created String 0 Created String 1 C
🌐
Red Hat
access.redhat.com › solutions › 7101058
java.lang.OutOfMemoryError thrown from StringBuilder/StringBuffer. - Red Hat Customer Portal
December 23, 2024 - java.lang.OutOfMemoryError is sometimes thrown from a StringBuilder/StringBuffer object with error messages like below even though Java Heap have not yet exhausted. (*e1) Exception example 1 in OpenJDK 8, 11 Exception in thread "main" java.lang.OutOfMemoryError at java.base/java.lang.AbstractStringBuilder.hugeCapacity(AbstractStringBuilder.java:214) at java.base/java.lang.AbstractStringBuilder.newCapacity(AbstractStringBuilder.java:206) at java.base/java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:173) at java.base/java.lang.AbstractStringBuilder.append(Abstrac
🌐
Coderanch
coderanch.com › t › 503084 › java › StringBuilder-memory-error
StringBuilder out of memory error (I/O and Streams forum at Coderanch)
July 16, 2010 - Because, you can see from the error message, the JVM does a arrayCopy when it expands the StringBuilder. If the StirngBuilder needs to be expanded whenever you append a char, then JVM will do this array copy again and again which consumes a lot of memory. I think you need to change your way of reading with buffering.
🌐
GitHub
github.com › tipsy › j2html › issues › 130
OutOfMemoryError: Java heap space · Issue #130 · tipsy/j2html
September 24, 2018 - java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf (Arrays.java:3332) at java.lang.AbstractStringBuilder.ensureCapacityInternal (AbstractStringBuilder.java:124) at java.lang.AbstractStringBuilder.append (AbstractStringBuilder.java:448) at java.lang.StringBuilder.append (StringBuilder.java:136) at java.lang.StringBuilder.append (StringBuilder.java:76) at java.lang.AbstractStringBuilder.append (AbstractStringBuilder.java:484) at java.lang.StringBuilder.append (StringBuilder.java:166) at java.lang.StringBuilder.append (StringBuilder.java:76) at j2html.tags.Tag.renderCloseTag (
Author   tipsy
🌐
tutorialpedia
tutorialpedia.org › blog › how-to-trim-stringbuilder-s-string
How to Trim a StringBuilder String Without Overhead: Avoiding toString().trim() and New Instances — tutorialpedia.org
StringBuilder.toString() creates a new String object by copying the contents of the StringBuilder’s internal character array. This involves allocating memory for a new String and copying every character (O(n) time complexity, where n is the length of the string).
Top answer
1 of 5
23

What is the reason for the OOM while creating a new string

Because you're running out of memory - or at least, the CLR can't allocate an object with the size you've requested. It's really that simple. If you want to avoid the errors, don't try to create strings that don't fit into memory. Note that even if you have a lot of memory, and even if you're running a 64-bit CLR, there are limits to the size of objects that can be created.

and why it doesn't throw OOM while writing to a file ?

Because you have more disk space than memory.

I'm pretty sure the code isn't exactly as you're describing though. This line would fail to compile:

sw.write(SB.ToString());

... because the method is Write rather than write. And if you're actually calling SB.ToString(), then that's just as likely to fail as str = SB.ToString().

It seems more likely that you're actually writing to the file in a streaming fashion, e.g.

using (var writer = File.CreateText(...))
{
    for (int i = 0; i < 5000; i++)
    {
        writer.Write(mytext);
    }
}

That way you never need to have huge amounts of text in memory - it just writes it to disk as it goes, possibly with some buffering, but not enough to cause memory issues.

2 of 5
14

Workaround: Suppose you would want to write a big string stored in StringBuilder to a StreamWriter, I would do a write this way to avoid SB.ToString's OOM exception. But if your OOM exception is due to StringBuilder's content add itself, you should work on that.

public const int CHUNK_STRING_LENGTH = 30000;
while (SB.Length > CHUNK_STRING_LENGTH )
{
    sw.Write(SB.ToString(0, CHUNK_STRING_LENGTH ));
    SB.Remove(0, CHUNK_STRING_LENGTH );
}
sw.Write(SB);
🌐
Post.Byes
post.bytes.com › home › forum › topic › c sharp
StringBuilder OutOfMemory - Post.Byes - Bytes
Since it is allocated piecemeal, you may be experiencing the result of memory fragmentation. This can be avoided by setting the Capacity to a high number before beginning the building of the String. Another possibility lies in the usage of the ToString method of the StringBuilder.
🌐
Baeldung
baeldung.com › home › java › java string › reuse stringbuilder for efficiency
Reuse StringBuilder for Efficiency | Baeldung
January 8, 2024 - StringBuilder objects are mutable, allowing us to change the object multiple times without creating a new object. This is significantly more performant than string manipulations. String objects are immutable, which means they cannot be modified after creation. When a String is modified, it creates a new object, which increases memory usage.