Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out of curiosity - is there a better performing approach to do this string replace?

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>,"");

  ...........................
}
like image 826
Jon Avatar asked Feb 08 '11 12:02

Jon


3 Answers

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.

like image 178
Daren Thomas Avatar answered Sep 25 '22 15:09

Daren Thomas


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);
}
like image 44
Guffa Avatar answered Sep 22 '22 15:09

Guffa


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.

like image 44
Aliostad Avatar answered Sep 25 '22 15:09

Aliostad