开发者

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 cas开发者_运维百科e 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.


In any case, you are lower-casing your original string here, which might not be a good thing?


It depends on a few things, how long the Filter string is etc.
So you will have to measure.

But I would expect a (single!) RegEx to be faster here.


If the provided code works for you, than this will be faster:

private void MyMethod(string Filter)
{
   //need to remove <Filter> and </Filter> case in-sensitive
   var result = Filter.ToLower().Replace("</filter>","");

  ...........................
}

as the first statement's result is ignored.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜