Reputation:
Is there anyway to improve the speed of this function. I use it a lot to get "ID Values" and I am thinking the way, how I am using it, is not the best one. Thanks in advance.
public string GetIDValues(string Elementnummer)
{
StringBuilder sb = new StringBuilder();
int totalCount = 0;
bool elementnummerAvailable = false;
foreach (var line in ElementHostContent)
{
if(line.Contains("= " + Elementnummer + ";"))
{
Regex regexElementbezeichner = new Regex(@";(\s*)\/\/ ([\w|\d].*)" );
var regexMatchElementbezeichner = regexElementbezeichner.Match(line);
var elementbezeichner = regexMatchElementbezeichner.Groups[2].ToString();
sb.AppendLine(elementbezeichner);
elementnummerAvailable = true;
}
totalCount++;
}
if (totalCount == ElementHostContent.Count() && elementnummerAvailable == true)
return sb.ToString().Trim();
else
return "/";
}
Inputs:
= 1234; // ABC DFG HIJ (CCC)
Elementnummer in this case is 1234
Upvotes: 0
Views: 120
Reputation: 11110
You are creating a new regular expression every time you need it. This is not fast. You should move the regex variable to a static field.
private static readonly Regex regexElementbezeichner = new Regex(@";(\s*)\/\/ ([\w|\d].*)" );
The Regex
class will parse your regex and convert it into an efficient state machine. If you throw it away every time, that's a significant cost.
Upvotes: 1
Reputation: 31616
Is there anyway to improve the speed
Yes. Avoid using *
(zero to many) and use +
(one to many). Regex is about patterns, and when the author introduces the zero, in zero to many, the regex parser has to backtrack to check all possibilities. This exhaustive backtracking takes up a majority of the time for the regex process.
This match group ([\w|\d].*)
looks like it is a prime candidate which has a lot of backtracking permutations and I would recommend refactoring it.
Upvotes: 0