c# - RegEx.IsMatch() vs. String.ToUpper().Contains() performance -


since there no case insensitive string.contains() (yet case insensitive version of string.equals() exists baffles me, digress) in .net, performance differences between using regex.ismatch() vs. using string.toupper().contains()?

example:

string teststring = "thisisastringwithinconsistentcapitalization";  bool containsstring = regex.ismatch(teststring, "string", regexoptions.ignorecase); bool containsstringregex = teststring.toupper().contains("string"); 

i've heard string.toupper() expensive call shy away using when want string.contains() comparisons, how regex.ismatch() compare in terms of performance?

is there more efficient approach doing such comparisons?

here's benchmark

using system; using system.diagnostics; using system.text.regularexpressions;  public class program {     public static void main(string[] args)     {         stopwatch sw = new stopwatch();          string teststring = "thisisastringwithinconsistentcapitalization";          sw.start();         var re = new regex("string", regexoptions.compiled | regexoptions.cultureinvariant | regexoptions.ignorecase);         (int = 0; < 1000000; i++)         {             bool containsstring = re.ismatch(teststring);         }         sw.stop();         console.writeline("rx: " + sw.elapsedmilliseconds);          sw.restart();         (int = 0; < 1000000; i++)         {             bool containsstringregex = teststring.toupper().contains("string");         }           sw.stop();         console.writeline("contains: " + sw.elapsedmilliseconds);          sw.restart();         (int = 0; < 1000000; i++)         {             bool containsstringregex = teststring.indexof("string", stringcomparison.ordinalignorecase) >= 0 ;         }           sw.stop();         console.writeline("indexof: " + sw.elapsedmilliseconds);     } } 

results

indexof (183ms) > contains (400ms) > regex (477ms)

(updated output times using compiled regex)


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -