It would be better to create regular expressions literally. Obviously, sometimes we have to use the large-consumption creation method new Regexp (). For example, regular expressions are used in syntax highlighting and formatting, the more Patten you need, the longer the time it takes. Firefox seems to have issued a warning in 12 seconds, and IE is directly suspended. In this case, we need to use the group storage method to improve ourProgramPerformance.
We usually have the following two options as our container, array or object. I will select the former, which is a little lighter. Next we will improve the performance of the hasclass function.
Original statement:
VaR hasclass = function (Ele, CLS) {return ELE. classname. match (New Regexp ('(\ s | ^)' + CLS + '(\ s | $ )'));}
Although it is short, too many assumptions are made, because the elements sometimes do not have classname, then directly return false. In addition, match returns an array, which is somewhat different from the expected Boolean value (it runs well before, thanks to the automatic conversion of JavaScript ). We use search instead of match:
VaR hasclass = function (Ele, CLS) {return ELE. classname. search (New Regexp ('(\ s | ^)' + CLS + '(\ s | $)')>-1 );}
I'm satisfied with the implementation of prototype. js. the test method is the most lightweight in all regular expressions (on the contrary, exec is the heaviest, slowest, and most powerful ):
VaR hasclass = function (El, CLS) {var classes = El. classname; Return (Classes> 0 )? (Classes = CLS | new Regexp ("(^ | \ s)" + CLS + "(\ s | $ )"). test (classes): false ;}
Until now, mining based on the regular expression method is unchangeable. We offer the cache algorithm:
(Function () {var C ={}; window. hasclass = function (El, CLS) {If (! C [CLS]) {C [CLS] = new Regexp ("(^ | \ s)" + CLS + "($ |\\ s )");} return el. classname & C [CLS]. test (El. classname );}})();
If this regular expression has been created before, there will be a previous regular expression that has not been created. Therefore, a large number of matchingAlgorithmVery advantageous. To prevent name conflicts, who would expect that a global variable C with the same name will be created later ?! Use is the same as the original one, because we reference it through the window.
test