Is there any difference in speed/memory usage for these two equivalent expressions:
Regex.IsMatch(Message, "1000")
Vs
Message.Contains("1000")
Any situations where one is better than other ?
The context of this question is as follows:
I was making some changes to legacy code which contained the Regex expression to find whether a string is contained within another string. Being legacy code I did not make any changes to that and in the code review somebody suggested that Regex.IsMatch should be replaced by string.Contains. So I was wondering whether the change was worth making.
For simple cases
String.Containswill give you better performance butString.Containswill not allow you to do complex pattern matching. UseString.Containsfor non-pattern matching scenarios (like the one in your example) and use regular expressions for scenarios in which you need to do more complex pattern matching.A regular expression has a certain amount of overhead associated with it (expression parsing, compilation, execution, etc.) that a simple method like
String.Containssimply does not have which is whyString.Containswill outperform a regular expression in examples like yours.