I have the below method where I need to check for some certain strings which could be in any case and then remove them. Just wondered if there was a better performing way?
private void MyMethod(string Filter)
{
//need to remove <Filter> and </Filter> case in-sensitive
var result = Filter.ToLower().Replace("<filter>","");
result = Filter.ToLower().Replace("</filter>,"");
...........................
}
Check this answer: Is there an alternative to string.Replace that is case-insensitive?
You might want to do a comparison with a performance check. Profile this with a profiler. It is the only way to really know, what is faster.
But honestly: Does performance really matter? How often are you doing this? I can't really see you doing this so often, that performance will become an issue...
You could try Regex.Replace
, with a case insensitive replace. This is not faster. But it is case insensitive.
One problem with that approach is that it will turn the entire string into lower case, not just make a case insensetive replace.
You can use a regular expression to do a case insensetive match:
string result = Regex.Replace(
Filter,
"</?filter>",
String.Empty,
RegexOptions.IgnoreCase
);
Another alternative is to use the IndexOf
method to locate the strings, as it can do a case insensetive search:
string result = Filter;
int index;
while ((index = IndexOf("<filter>", StringComparison.OrdinalIgnoreCase)) != -1) {
result = result.Remove(index, 8);
}
while ((index = IndexOf("</filter>", StringComparison.OrdinalIgnoreCase)) != -1) {
result = result.Remove(index, 9);
}
Replace
calls to unmanaged code which is implemented in C++ which I imagine will be hard to beat.
However, I can see you keep using .ToLower()
which you can cut down to one call and keeping the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With