Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created November 19, 2012 09:54
Show Gist options
  • Save jonelf/4109899 to your computer and use it in GitHub Desktop.
Save jonelf/4109899 to your computer and use it in GitHub Desktop.
Replace replace linq regex
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();
}
}
}
@jonelf
Copy link
Author

jonelf commented Nov 19, 2012

Example output:
Replace replace:220
Linq replace:694
Regex replace:1455

@jonelf
Copy link
Author

jonelf commented Nov 19, 2012

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