Code _ javascript

Source: Internet
Author: User
I can see that the project uses the js array split method to format the query string. Why cannot I use regular expressions? What is the performance? If you are interested, you can study it. You can see that the project uses the js array split method to format the query string. Why can't you use regular expressions? What is the performance? The following code is available:

The Code is as follows:


Var url = 'www .baidu.com? A = 123 & B = 456 & c = 789 & e = dfsdfsdfsdfsdfsdf & f = 46545454545454785 & g = e23232dsfvdfvdf ';
/**
* Format the query string (regular expression)
* @ Param url
* @ Return {Object} formatted json Object
*/
Function formatUrl (url ){
Var reg = /(? :[? &] +) ([^ &] +) = ([^ &] +)/G;
Var data = {};
Function fn (str, pro, value ){
Data [decodeURIComponent (pro)] = decodeURIComponent (value );
}
Url. replace (reg, fn );
Return data;
}
/**
* Format the query string (Array Implementation)
* @ Param url
* @ Return {Object} formatted json Object
*/
Function formatUrl2 (url ){
Url = url. replace (/.*\? /,'');
Var args = {},
Items = url. length? Url. split ("&"): []
, Item = null
, I = 0
, Len = items. length;
For (I = 0; I Item = items [I]. split ("= ");
Args [decodeURIComponent (item [0])] = decodeURIComponent (item [1]);
}
Return args;
}
Var startTime = new Date ();
For (var I = 0; I <1000000; I ++ ){
FormatUrl2 (url );
}
Console. log ('formaturl2 ', (new Date ()-startTime); // formatUrl2 12138
StartTime = new Date ();
For (var I = 0; I <1000000; I ++ ){
FormatUrl (url );
}
Console. log ('formaturl', (new Date ()-startTime); // formatUrl 12537


The test browser is chrme 25; the regular expression function is slower than the function implemented by the array ....). But fortunately, it takes only 1 million seconds to repeat the execution for 0.4 times.

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.