I recently had the need to validate some properties using Regex, after doing it, and see what refers to performance, I notice that it is much slower than, in my case (C #) perform a similar validation using linq
For example (C #)
List<string> Lista = new List<string>();
for(int i = 0; i<100; i++)
{
//Método que devuelve un número que cumple
Lista.Add(GenerarNumeroCorrecto());
//Método que devuelve un campo que no cumple
Lista.Add(GenerarNumeroIncorrecto());
}
Stopwatch s = new Stopwatch();
s.Start();
foreach(string cadena in Lista)
{
if((!cadena.Any(c => !char.IsDigit(c))) && cadena.Length == 7)
{
//true
}
}
s.Stop();
var LinqElapsed = s.Elapsed;
s.Reset();
s.Start();
Regex reg = new Regex("^\d{7}$");
foreach(string cadena in Lista)
{
if (reg.IsMatch(cadena))
{
//true
}
}
s.Stop();
var RegexElapsed = s.Elapsed;
Console.WriteLine("Linq: demora {0} \nRegex: demora {1}",LinqElapsed,RegexElapsed);
Console.ReadLine();
}
In the previous example, the output is as follows:
Linq: delay 00: 00: 00.0001753
Regex: delay 00: 00: 00.0007208
The solution with Regex is more than 4 times slower, and hence the doubt, why regex is so slow? , what is its real function behind causing this?