Created
November 19, 2012 09:54
-
-
Save jonelf/4109899 to your computer and use it in GitHub Desktop.
Replace replace linq regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Stopwatch stopWatch = new Stopwatch(); | |
String str = "123456#*42#"; | |
stopWatch.Start(); | |
for (int i = 0; i < 1000000; i++) | |
{ | |
var result = str.Replace("*", "").Replace("#", ""); | |
} | |
stopWatch.Stop(); | |
Console.WriteLine("Replace replace:" + stopWatch.ElapsedMilliseconds); | |
stopWatch.Restart(); | |
for (int i = 0; i < 1000000; i++) | |
{ | |
var tmp = new StringBuilder(); | |
var len = str.Length; | |
for (int j = 0; j < len; j++) | |
{ | |
if (str[j] != '#' && str[j] != '*') | |
tmp.Append(str[j]); | |
} | |
var result = tmp.ToString(); | |
} | |
stopWatch.Stop(); | |
Console.WriteLine("Stringbuilder replace:" + stopWatch.ElapsedMilliseconds); | |
stopWatch.Restart(); | |
for (int i = 0; i < 1000000; i++) | |
{ | |
var result = string.Join("", | |
str.Select(r => char.IsDigit(r) ? r.ToString() : "")); | |
} | |
stopWatch.Stop(); | |
Console.WriteLine("Linq replace:" + stopWatch.ElapsedMilliseconds); | |
stopWatch.Restart(); | |
for (int i = 0; i < 1000000; i++) | |
{ | |
var result = Regex.Replace(str, @"[#\*]", string.Empty); | |
} | |
stopWatch.Stop(); | |
Console.WriteLine("Regex replace:" + stopWatch.ElapsedMilliseconds); | |
Console.Read(); | |
} | |
} | |
} |
Added stringbuilder replace:
Replace replace:226
Stringbuilder replace:147
Linq replace:699
Regex replace:1459
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output:
Replace replace:220
Linq replace:694
Regex replace:1455