I would like to know whats faster. Help me out.
I have a variable declared in a Method like so:
public static Regex FindNumber()
{ return new Regex(@"\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); }
As you can see it returns a Regular Expression.
I also have another Method that looks like so:
private static string TestOne(string RawData)
{
Regex rgxFindNumber = FindNumber();
Regex rgxFindDays = FindDays();
for (int i = 0; i < mc.Count; i++)
{
int days = Convert.ToInt32(rgxFindNumber.Match(rgxFindDays.Match(mc[i].Value).Value).Value);
}
return RawData;
}
Now is the TestOne Method going to be faster or is TestTwo?
private static string TestTwo(string RawData)
{
for (int i = 0; i < mc.Count; i++)
{
int days = Convert.ToInt32(FindNumber().Match( FindDays().Match(mc[i].Value).Value).Value);
}
return RawData;
}
Now im curious because TestOne Can get called a aweful lot in my code so I would like to know what would be better to implement.
Thanks guys.
**Edit:**The code I am using has an extremely large class. Its a text parser for a text based strategy game. I am trying to refactor it a bit and thats what I am wondering here. If I do create a private variable for the Regex, wouldn’t it be run every time the class is accessed? Thats my question to you.
TestOnewill be faster thanTestTwo, because you’re not creating a new regular expression for every loop iteration.This has two benefits:
mc.CounttimesHowever, I would go one step further. If you’re always going to return that same regular expression, and you’re concerned about speed, I would cache that regex object in a static field.
For instance, you might consider this:
This would create just one object, total, and keep it around.
However, and here’s my real answer.
To actually know which one is going to be the fastest, you’re going to have to measure your code, optionally with my variant thrown in for good measure, and then decide. Never decide on optimizations without hard data, you might end up spending time rewriting code, which can introduce new bugs, which will need fixing, which you will spend more time on, only to eek out another 1% of performance.
The big optimizations are done algorithmically, like changing the type of sorting algorithm, and then only afterwards, if necessary, you move on to local optimizations like loop tuning.
Having said that, I would at least avoid constructing the object in the loop, that’s just common sense.