TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Regex Versus Loop: Use For Loop Instead of Regex

Test the performance of Regex.IsMatch versus a for-loop. A for-loop can be used to optimize programs.
Regex, loop. Regular expressions can be re-implemented with loops. For example, a loop can make sure that a string only contains a certain range of characters. Using Regex is less clear and far slower in runtime performance.Optimization
Example. The goal of this program is to validate the string parameter. The string must only contain the characters "a" through "z" lowercase and uppercase, and the ten digits "0" through "9".

Note: This is of practical use on some websites and programs that parse data that may not be well-formed.

Here: The two methods IsValid1 and IsValid2 have very different implementations but their results are the same.

IsValid1: This method uses Regex.IsMatch to tell whether the string only has the range of characters specified.

Regex

IsValid2: This uses a for-loop to iterate through the character indexes in the string. It employs a switch on the char.

ForSwitch
C# program that validates strings using System; using System.Text.RegularExpressions; class Program { static void Main() { Console.WriteLine(IsValid1("dotnetCodex100")); Console.WriteLine(IsValid2("dotnetCodex100")); Console.WriteLine(IsValid1("$Invalid")); Console.WriteLine(IsValid2("$Invalid")); Console.WriteLine(IsValid1("900DOTNETPERLS")); Console.WriteLine(IsValid2("900DOTNETPERLS")); Console.WriteLine(IsValid1(" space ")); Console.WriteLine(IsValid2(" space ")); } public static bool IsValid1(string path) { return Regex.IsMatch(path, @"^[a-zA-Z0-9]*$"); } public static bool IsValid2(string path) { for (int i = 0; i < path.Length; i++) { switch (path[i]) { case 'a': // Lowercase case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': // Uppercase case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '0': // Numbers case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { continue; } default: { return false; // Illegal } } } return true; // Legal } } Output True True False False True True False False
Benchmark. We measure the two methods. The first two strings in the example are tested in tight loops. The final result indicates the number of nanoseconds that the method invocations required.

Results: IsValid1 (with Regex.IsMatch) required about 906 nanoseconds. IsValid2 (with switch) required about 13 nanoseconds.

So: The regular expression version required almost 70 times more processing time.

Benchmark description 1000000 loops with 2 method calls in each iteration. Numbers reported in nanoseconds per method call. Code tested in loops if (IsValid1("dotnetCodex100")) // Body 1 start { } if (IsValid1("$Invalid")) { } if (IsValid2("dotnetCodex100")) // Body 2 start { } if (IsValid2("$Invalid")) { } Benchmark results IsValid1: 906.665 ns (Uses regular expression) IsValid2: 13.500 ns (Uses switch, faster)
Regex.IsMatch. The Regex.IsMatch method performs the logic of the Regex.Match internally, but narrows the result information to a Boolean value. This indicates whether any matching text was found or not.

Note: The Regex.IsMatch method is commonly used in if-statements to see if the string contains the pattern specified.

Summary. You can test the validity of string input against a set of characters. We used the Regex.IsMatch method to check against a range of characters. We used the switch statement on an iterative loop for better performance.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf