c# - Fastest way to remove chars from string -


I have a string from which I have to remove the following four: '\ r', '\ n', and T '. I have tried three different ways to remove these four and have benchmarked them so that I can get the fastest solution.

The following are the methods and when I run them 1000000 times:

If I have the fastest solution to remove 1 or 2 characters. But as I put in more characters, it starts taking too much time

  str = str.Replace ("\ r", string.Empty). ("\ N", "string \\"). Change ("\ t", string.Empty);  

Execution time = 1695

For 1 or 2 characters, it was slow, string was found. Replay, but it looks better for 3 characters.

  string [] split = str.Split (new letter [] {'\ t', '\ r', '\ n'}, StringSplitOptions.None); Str = split.Aggregate & lt; String & gt; ((Str1, str2) => str1 + str2);  

Execution time = 1030

with the slowest of all, even 1 character. Maybe my regular expression is not the best.

  str = Regex.Replace (str, "[\ r \ n \ t]", string.Empty, RegexOptions.Compiled);  

Execution time = 3500

These are the three solutions I came up with.

string which I used for benchmarking:

  stringbuilder builder = new stringbiller (); Builder.AppendFormat ("{0} \ r \ n {1} \ t \ t \ r \ n {2} \ t \ r \ n {3} \ r \ n {4} \ t \ t \ r \ N {5} \ r \ n {6} \ r \ n {7} \ r \ n {8} \ r \ n {9} "," SELECT "," [Extent1]. [Customer ID] Customer name [title] as [title], "[extent1]. [First name] as [first name],", "[extant 1]." [Middle name] AS [Middle name], "," [ Extant 1]. [LastLime] AS [LastLime], "," [Extant 1]. [Suffix] AS [Suffix], "," [Extent 1]. [Company Name] as [Company Name], "," [ Extant 1]. [Salespeason] AS [Salespecer], "); String Str = builder.tostring ();  

here uber-fast unsecured version, version 2 .

  public stable insecure string StripTabsAndNewlines (strings) {int len ​​= s.Length; char * newChars = stackalloc char [lane]; char * current = new chars; Int i = 0; i & lt; len; ++ i) {char c = s [i]; switch (c) {case '\ r': case '\ n': case '\ t': continue; Default: * currentChar ++ = c; break; }} Return new string (new chars, 0, (int) (current office - new chars)); }  

And there are Benchmarks (100,000 strips stripe time in MS)

 cornerback84's string Replace: 9433 Andy West's String.Connect: 4756 Four Array of AviJ: 1374 Four Holes of Matt Howells: 1163 

Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -