4

Possible Duplicate:
Regex.IsMatch vs string.Contains

Which is faster, preferable and why?

What the difference in mechanisms between two?

I need to search for some values from UserAgent, most of values can be used without wildcards (e.g. if I want to catch cellular phones I search for iPhone instead of *iPhone* wildcards).

Community
  • 1
  • 1
eugeneK
  • 10,750
  • 19
  • 66
  • 101
  • I think you may try to run a benchmark? – Julius F Jul 06 '10 at 12:51
  • No, there is no answer i need in there. – eugeneK Jul 06 '10 at 12:58
  • 1
    @daemonfire300, i wouldn't ask this question if i wanted to run a benchmark. I thought some ppl already know or do know mechanism behind each method. – eugeneK Jul 06 '10 at 12:59
  • How to do search, whether via one to one element comparison or by patterns is well covered by algorithms literature. Study these, and understand why the first rule of optimisation is "Don't"; then you will understand why these comments and answers are the way they are. – Richard Jul 06 '10 at 13:08

1 Answers1

14

What is faster

Try measuring. But this is the wrong question, see below.

preferable

If I want to match a fixed string String.Contains does just what I need. If I need to pattern match, then String.Contains is useless.

Comparing the performance of these is irrelevant, they do completely different things. Use the right tool first, and only then if your performance is a problem use profiling to identify hot parts of your code to look at.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • If Regex performs faster due to better algorithm why should i use Contains? I don't need this for little small search but for a complex one where lowest execution time is urgent – eugeneK Jul 06 '10 at 12:56
  • 1
    @eugeneK: Regex support complex matching logic (consider how to implement regex matching). It would be hard to make a direct string comparison as slow. – Richard Jul 06 '10 at 13:04