Implement code _javascript techniques through regular formatting of URL query strings

Source: Internet
Author: User
See the project through the JS array split method format query string, the whim why not use the regular then, how performance? So we have the following code:
Copy Code code as follows:

var url= ' www.baidu.com?a=123&b=456&c=789&e=dfsdfsdfsdfsdfsdfsdf&f=46545454545454785&g= E23232DSFVDFVDF ';
/**
* Format query string (Regular implementation)
* @param URL URL address
* @return JSON object formatted with {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 query string (array implementation)
* @param URL URL address
* @return JSON object formatted with {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<items.length;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 function of the regular implementation is slower than the function of the array implementation (tears running ...). )。 But luckily, it's only 0.4 seconds to repeat 1 million 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.