I have a function going through a line that searches for a template and changes its parts. I could optimize it by inserting
if (!text.Contains(pattern)) return;
But I really go through the entire line and compare its parts with the template, so the question is, how does it work String.Contains()? I know there was such a question - How does String.Contains work? but the answer is rather unclear. So, if String.Contains()looking through the entire array of characters and comparing them with the template I'm looking for, it would not make my function faster, but slower.
So, is it a good idea to try such an optimization? And - is it possible that it String.Contains()will be even faster than a function that just goes through the entire array and compares each individual character with some constant?
Here is the code:
public static char colorchar = (char)3;
public static Client.RichTBox.ContentText color(string text, Client.RichTBox SBAB)
{
if (text.Contains(colorchar.ToString()))
{
int color = 0;
bool closed = false;
int position = 0;
while (text.Length > position)
{
if (text[position] == colorchar)
{
if (closed)
{
text = text.Substring(position, text.Length - position);
Client.RichTBox.ContentText Link = new Client.RichTBox.ContentText(ProtocolIrc.decode_text(text), SBAB, Configuration.CurrentSkin.mrcl[color]);
return Link;
}
if (!closed)
{
if (!int.TryParse(text[position + 1].ToString() + text[position + 2].ToString(), out color))
{
if (!int.TryParse(text[position + 1].ToString(), out color))
{
color = 0;
}
}
if (color > 9)
{
text = text.Remove(position, 3);
}
else
{
text = text.Remove(position, 2);
}
closed = true;
if (color < 16)
{
text = text.Substring(position);
break;
}
}
}
position++;
}
}
return null;
}
source
share