String.replace vs StringBuilder.replace for memory

I downloaded the stream as byte [] of 'raw', which is about 36 MB. Then I convert this to string using

string temp = System.Text.Encoding.UTF8.GetString(raw) 

Then I need to replace all "\ n" with "\ r \ n", so I tried

  string temp2 = temp.Replace("\n","\r\n") 

but he chose the exception "Out of Memory". Then I tried to create a new string using StringBuilder:

 string temp2 = new StringBuilder(temp).Replace("\n","\r\n").toString() 

and this exception did not choose. Why is there a memory problem in the first place (here I deal only with 36 MB), but also why does StringBuilder.Replace () work when the other is not working?

+7
source share
4 answers

Using:

 string temp2 = temp.Replace("\n","\r\n") 

for each match "\ n" in the temp line, the system creates a new line with a replacement.

This does not happen with StringBuilder because StringBuilder is changed, so you can actually change the same object without having to create another.

Example:

 temp = "test1\ntest2\ntest3\n" 

With the first method (string)

 string temp2 = temp.Replace("\n","\r\n") 

equivalently

 string aux1 = "test1\r\ntest2\ntest3\n" string aux2 = "test1\r\ntest2\r\ntest3\n" string temp2 = "test1\r\ntest2\r\ntest3\r\n" 

Using the Secon Method (StringBuilder)

 string temp2 = new StringBuilder(temp).Replace("\n","\r\n").toString() 

equivalently

 Stringbuilder aux = "test1\ntest2\ntest3\n" aux = "test1\r\ntest2\ntest3\n" aux = "test1\r\ntest2\r\ntest3\n" aux = "test1\r\ntest2\r\ntest3\r\n" string temp2 = aux.toString() 
+5
source

The following StringBuilder from MSDN :

Most methods that modify an instance of this class return a reference to the same instance, and you can call a method or property by reference. This can be convenient if you want to write a single statement that has entire sequences of operations.

Therefore, when you call replace in String, a new object (big data - 36MB) will be allocated to create a new line. But StringBuilder accesses the same instance objects and does not create a new one.

+3
source

There is a concept of memory pressure, which means that the more temporary objects are created, the more often garbage collection works.

So: StringBuilder creates fewer temporary objects and reduces memory pressure.

StringBuilder Memory

Replace

Next, we use StringBuilder to replace characters in loops. Convert the string to StringBuilder first, and then call the StringBuilder methods. It's faster - the StringBuilder type uses internal character arrays

+1
source

The string is immutable in C #. If you use the string.replace () method, the system will create a String object for each replacement. The StringBuilder class helps you avoid creating an object.

0
source

All Articles