Monday, September 03, 2007

Trim Vs Replace for \r \n

Which is the better way to remove occurrences of \r \n from the ends of a string ? i used to use two replace operations on the string, but i think there is more efficient method using Trim().

I thought of comparing out the performances of both operations. Following is the code i wrote.


DateTime time = DateTime.Now;

for (int i = 0; i <>

{

string ABC = @"\r\n\r+CMT: \r\n\r\n";

ABC = ABC.Trim(new char[] { '\r', '\n' });

}

double TimeTaken = (DateTime.Now - time).TotalMilliseconds;

Console.WriteLine(string.Format("For Trim Taken {0}", TimeTaken));

time = DateTime.Now;

for (int i = 0; i <>

{

string ABC = @"\r\n\r+CMT: \r\n\r\n";

ABC = ABC.Replace('\r', '\0').Replace('\n', '\0');

}

TimeTaken = (DateTime.Now - time).TotalMilliseconds;

Console.WriteLine(string.Format("For Replace Taken {0}", TimeTaken));



The performance of Trim was far better than that of Replace.The difference in time is prominent. Further more its better to use it when string may contain \r \n characters within in (other than ends).