c# - string.replace vs StringBuilder.replace for memory -


this question has answer here:

i have downloaded stream byte[] 'raw' 36mb. convert string with

string temp = system.text.encoding.utf8.getstring(raw) 

then need replace "\n" "\r\n" tried

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

but threw "out of memory" exception. tried create new string stringbuilder:

string temp2 = new stringbuilder(temp).replace("\n","\r\n").tostring() 

and didn't throw exception. why there memory issue in first place (i'm dealing 36mb here), why stringbuilder.replace() work when other doesn't?

when use:

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

for every match of "\n" in string temp, system creates new string replacement.

with stringbuilder doesn't happens because stringbuilder mutable, can modify same object without need create one.

example:

temp = "test1\ntest2\ntest3\n" 

with first method (string)

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

is equivalent to

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

with secon method (stringbuilder)

string temp2 = new stringbuilder(temp).replace("\n","\r\n").tostring() 

is equivalent to

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() 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -