Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest way to remove chars from string
    primarykey
    data
    text
    <p>I have a string from which I have to remove following char: '\r', '\n', and '\t'. I have tried three different ways of removing these char and benchmarked them so I can get the fastest solution.</p> <p>Following are the methods and there execution time when I ran them 1000000 times:</p> <p>It should be fastest solution if I have 1 or 2 char to remove. But as I put in more char, it starts to take more time</p> <pre><code>str = str.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty); </code></pre> <p><strong>Execution time = 1695</strong></p> <p>For 1 or 2 char, this was slower then String.Replace, but for 3 char it showed better performance.</p> <pre><code>string[] split = str.Split(new char[] { '\t', '\r', '\n' }, StringSplitOptions.None); str = split.Aggregate&lt;string&gt;((str1, str2) =&gt; str1 + str2); </code></pre> <p><strong>Execution time = 1030</strong></p> <p>The slowest of all, even with 1 char. Maybe my regular expression is not the best.</p> <pre><code>str = Regex.Replace(str, "[\r\n\t]", string.Empty, RegexOptions.Compiled); </code></pre> <p><strong>Execution time = 3500</strong></p> <p>These are the three solutions I came up with. Is there any better and faster solution that anyone here know, or any improvements I can do in this code?</p> <p><strong>String</strong> that I used for benchmarking:</p> <pre><code>StringBuilder builder = new StringBuilder(); builder.AppendFormat("{0}\r\n{1}\t\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].[CustomerID] AS [CustomerID], ", "[Extent1].[NameStyle] AS [NameStyle], ", "[Extent1].[Title] AS [Title], ", "[Extent1].[FirstName] AS [FirstName], ", "[Extent1].[MiddleName] AS [MiddleName], ", "[Extent1].[LastName] AS [LastName], ", "[Extent1].[Suffix] AS [Suffix], ", "[Extent1].[CompanyName] AS [CompanyName], ", "[Extent1].[SalesPerson] AS [SalesPerson], "); string str = builder.ToString(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload