My own bench marks appear to contradict user279470's benchmark results.
In my use case I wanted to check a simple Regex with some OR operators for 4 values versus doing 4 x String.Contains()
.
Even with 4 x String.Contains()
, I found that String.Contains()
was 5 x faster.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text.RegularExpressions;
namespace App.Tests.Performance
{
[TestClass]
public class PerformanceTesting
{
private static Random random = new Random();
[TestMethod]
public void RegexVsMultipleContains()
{
var matchRegex = new Regex("INFO|WARN|ERROR|FATAL");
var testStrings = new List<string>();
int iterator = 1000000 / 4; // div 4 for each of log levels checked
for (int i = 0; i < iterator; i++)
{
for (int j = 0; j < 4; j++)
{
var simulatedTestString = RandomString(50);
if (j == 0)
{
simulatedTestString += "INFO";
}
else if (j == 1)
{
simulatedTestString += "WARN";
}
else if (j == 2)
{
simulatedTestString += "ERROR";
}
else if (j == 3)
{
simulatedTestString += "FATAL";
}
simulatedTestString += RandomString(50);
testStrings.Add(simulatedTestString);
}
}
int cnt;
Stopwatch sw;
//////////////////////////////////////////
// Multiple contains test
//////////////////////////////////////////
cnt = 0;
sw = new Stopwatch();
sw.Start();
for (int i = 0; i < testStrings.Count; i++)
{
bool isMatch = testStrings[i].Contains("INFO") || testStrings[i].Contains("WARN") || testStrings[i].Contains("ERROR") || testStrings[i].Contains("FATAL");
if (isMatch)
{
cnt += 1;
}
}
sw.Stop();
Console.WriteLine("MULTIPLE CONTAINS: " + cnt + " " + sw.ElapsedMilliseconds);
//////////////////////////////////////////
// Multiple contains using list test
//////////////////////////////////////////
cnt = 0;
sw = new Stopwatch();
sw.Start();
var searchStringList = new List<string> { "INFO", "WARN", "ERROR", "FATAL" };
for (int i = 0; i < testStrings.Count; i++)
{
bool isMatch = searchStringList.Any(x => testStrings[i].Contains(x));
if (isMatch)
{
cnt += 1;
}
}
sw.Stop();
Console.WriteLine("MULTIPLE CONTAINS USING LIST: " + cnt + " " + sw.ElapsedMilliseconds);
//////////////////////////////////////////
// Regex test
//////////////////////////////////////////
cnt = 0;
sw = new Stopwatch();
sw.Start();
for (int i = 0; i < testStrings.Count; i++)
{
bool isMatch = matchRegex.IsMatch(testStrings[i]);
if (isMatch)
{
cnt += 1;
}
}
sw.Stop();
Console.WriteLine("REGEX: " + cnt + " " + sw.ElapsedMilliseconds);
}
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
}
}