Improving the efficiency of C # Regular Expressions

Source: Internet
Author: User

Speaking of C #'s Regex, the most talked about should be RegexOptions. compiled: RegexOptions in terms of matching speed. compiled can improve the matching speed, but RegexOptions is used in the startup speed. compiled usually slows down the startup, which is said to be up to 60 times faster.

Conduct a group of tests and have test data before discussion.

The first step is to test the hardware information on the post (haha, the hardware is a bit bad :()

Step 2,

A. test if RegexOptions. Compiled item is not used, use some content at will, and then instantiate the regular expression object 10 thousand times in a loop to match the content.

Code
 protected void Page_Load(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
string content = webClient.DownloadString("http://www.cnblogs.com/tmyh/archive/2010/09/29/sqlindex_01.html");

Stopwatch watcher = new Stopwatch();
watcher.Start();

int i = 10000;
while (i > 0)
{
Regex rgx = new Regex("<div>.+?</div>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
bool b1 = rgx.IsMatch(content);

Regex rgx2 = new Regex("<p>.+?</p>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
bool b2 = rgx2.IsMatch(content);

i--;
}
Response.Write(string.Concat("<div>", watcher.Elapsed.TotalSeconds.ToString("f7"), "</div>"));
}

 

The execution shows that the memory usage is 39,760 kb. The output execution time is 3.7954446 seconds (the shortest time is obtained after several clicks)

B. Test the situation when RegexOptions. Compiled item is used. Use some content at will, and then instantiate the regular expression object 10 thousand times in a loop to match the content.

Code
 protected void Page_Load(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
string content = webClient.DownloadString("http://www.cnblogs.com/tmyh/archive/2010/09/29/sqlindex_01.html");


Stopwatch watcher = new Stopwatch();
watcher.Start();

int i = 10000;
while (i > 0)
{
Regex rgx = new
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.