Yesterday, in the group. some people have discussed that regular expressions are good and can be verified to avoid abnormal performance loss. as a result, we will talk about this topic. some people say that regular expressions consume a lot of energy. some people say that abnormal energy consumption is not much...
I conducted a test based on my point of view that I didn't have the right to speak. The results are as follows:
Unit (MS) |
First compilation |
Second |
Third time |
Fourth |
Fifth |
Recompile |
regular expression test |
0 |
0 |
0 |
0 |
0 |
0 |
exception test |
43 |
23 |
20 |
15 |
17 |
41 |
cyclic test 0.1 million times |
0 |
0 |
0 |
0 |
0 |
0 |
cyclic test 1 million times |
3 |
3 |
3 |
3 |
3 |
3 |
Cyclic Testing 10 million times |
33 |
33 |
33 |
33 |
33 |
34 |
Explanation:
During the first compilation, the exception takes a lot of time, the cycle 0.1 million times takes 0 ms, and the cycle 1 million times is 3 ms. Each refresh is fixed and remains unchanged.
The second exception ~ The fifth time (not re-compiled). There are changes to the refresh, which lingers around 15 ~ Between 27ms, while regular expressions are always stable for 0 ms.
To sum up, the exception takes a lot of time... (compared with the loop test, you can know)
The following are the testsCodeFragment:
Public partial class regextest: system. web. UI. page {private const string test_data = "2009-02-40"; protected void page_load (Object sender, eventargs e) {testregex (); testtrycatch (); testwhile ();} private void testwhile () {stopwatch Sw = new stopwatch (); Sw. start (); For (INT I = 0; I <10000000; I ++) {} SW. stop (); label1.text + = "loop 10000000 test:" + SW. elapsedmilliseconds + "Ms" + "<br/>";} p Rivate void testregex () {stopwatch Sw = new stopwatch (); Sw. start (); bool isdate = RegEx. ismatch (test_data, @ "^ (1 [6-9] | [2-9] \ D) \ D {2})-(0? [1, 13578] | 1 [02])-(0? [1-9] | [12] \ d | 3 [01]) | (1 [6-9] | [2-9] \ D) \ D {2})-(0? [13456789] | 1 [012])-(0? [1-9] | [12] \ d | 30) | (1 [6-9] | [2-9] \ D) \ D {2 }) -0? 2-(0? [1-9] | 1 \ d | 2 [0-9]) | (1 [6-9] | [2-9] \ D) (0 [48] | [2468] [048] | [13579] [26]) | (16 | [2468] [048] | [3579] [26]) 00)-0? 2-29-) $ "); label1.text + =" regular expression: "+ (isdate = true? "Date data": "non-date data") + "<br/>"; Sw. stop (); label1.text + = "Regular Expression test:" + SW. elapsedmilliseconds + "Ms" + "<br/>";} private void testtrycatch () {stopwatch Sw = new stopwatch (); Sw. start (); try {datetime n = convert. todatetime (test_data); label1.text + = "exception judgment: Date data <br/>";} catch {label1.text + = "exception judgment: non-date data <br/> ";} SW. stop (); label1.text + = "exception test:" + SW. elapsedmilliseconds + "Ms" + "<br/> ";}}