The performance _javascript of JS regular expression by trim prototype function

Source: Internet
Author: User
Tags cdata regular expression trim
In general, the regular wording is:
<script type= "Text/javascript" >//<! [Cdata[String.prototype.trim = function () {return this.replace (/^[\s\t]+|[ \s\t]+$/g, ""); } s = ' never-online\ ' weblog, www.jb51.net scripthome '; Alert (S.trim (). length); ]]></script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

If you encounter a variable-length string of large data, you will find that this is a resource consuming. Efficiency is not high, sometimes even unbearable.
<textarea id="runcode87319"><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" > <ptml> <pead> & Lt;meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/> <title></title> <meta http-equiv= Pragma" content= "No-cache"/> <meta http-equiv= "Cache-control" content= "No-cache"/> <meta http-equiv= "Expires" content= "0"/> <meta http-equiv= "Imagetoolbar" content= "no"/> <style type= "text/css" title= "Default" media= "screen" >/*<! [cdata[*//*]]>*/</style> </pead> <body> <textarea> Please write a sufficient number of spaces or tab characters here. </textarea> <script type= "Text/javascript" >//<! [Cdata[String.prototype.trim = function () {return this.replace (/^[\s\t]+|[ \s\t]+$/g, ""); var s = document.getelementsbytagname (' textarea ') [0].value var d = new Date (); S.trim (); Alert (new Date ()-D); ]]></script> </body> </ptml></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

In explaining this reason, I think of the previous see master regular expression inside mentioned. There is a difference between an NFA and a DFA's engine. Js/perl/php/java/.net are all NFA engines.
And the difference between the DFA and the NFA mechanism brings 5 effects:
1. The DFA only scans once for each character in the text string, relatively fast, but less characteristic; the NFA has to toss and turn over the characters, the words, slow, but rich, so it's widely used, and today's major regular expression engines, such as Perl, Ruby, Python's re modules, The Regex libraries for Java and. NET are NFA.
2. Only the NFA supports lazy and backreference (post reference) characteristics;
3. NFA eager to desire, so the most Zokozheng-style priority matching success, so occasionally miss the best match results, the DFA is "the longest Zokozheng-style priority matching success."
4. NFA defaults to the use of greedy quantifiers (that is, for/.*/,/\w+/such a "repeat n" mode, in a greedy manner, as much as possible to match more characters, until not to stop), the NFA will give priority to match quantifiers.
5. The NFA may fall into the trap of recursive calls and performance is extremely poor.

Backtracking (back to the moon)
When the NFA found himself eating too much, one by one spit, side spit to find a match, this process is called backtracking. Because of this process, in the NFA matching process, especially in the preparation of unreasonable regular matching process, the text is repeatedly scanned, the efficiency of the loss is not small. Understanding this is helpful for writing efficient regular expressions.

Positioning/Analysis Reasons
At the time of explaining the above trim prototype method. After testing, not to say whether the results are correct, there are several ways to resolve the JS NFA engine back to the number of times
A. Remove the quantifier that is qualified, namely change to
Copy Code code as follows:

String.prototype.trim = function () {
Return This.replace (/^[\s\t]+|[ \s\t]$/g, "");
}

B. Remove the tail of the string match. is changed to:
Copy Code code as follows:

String.prototype.trim = function () {
Return This.replace (/^[\s\t]+/g, ");
}

C. Add multiple line matches. is changed to:
Copy Code code as follows:

String.prototype.trim = function () {
Return This.replace (/^[\s\t]+|[ \s\t]+$/mg, "");
}

From the above three kinds of changes in combination with the beginning of the NFA data, we can probably know the reasons for the problem of trim performance
Quantifier qualification will match precedence.
Quantifier limit at the end may make JS regular engine back, there is a recursive trap, this recursive depth is too deep. If the string is larger, the stack overflow should occur.
Since multiple lines can match, and performance is not consuming much. There is no problem with performance, and from the point of view of a person who writes this regular program, many lines are significantly more than the empty strings to be replaced by a single line. So the 2nd conclusion should be right.
Improved
First of all, it is no efficient problem to determine the beginning of a matching string. Performance problems occur at the end of the match, which can be combined with a combination of regular and traditional to improve the trim performance problem.
For example:
<script type= "Text/javascript" >//<![ cdata[String.prototype.trim = function () {var s = this.replace (/^[\s\t]+/g, '); Start looking from the back end of S and loop back to the last Non-empty string, code slightly. }//]]></script>
[ctrl+a All selected note: If you need to introduce external JS need to refresh to perform]

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.