JavaScript parsing JSON string Performance comparison analysis code _json

Source: Internet
Author: User
Tags eval wrapper
The method used in parsing is typically an eval or new function, and the current IE8 and Firefox3.1 are built with native JSON objects (supposedly a certain performance boost). So how do we choose from these three methods (because of the performance problem, regardless of the JavaScript implementation parsing) when we actually use them? In the face of many browsers, which way is the best performance?

First, test methods

1. First specify the number of tests and JSON strings

Copy Code code as follows:

var count = 10000, o = null, i = 0, jsonstring = ' {' value ': {"items": [{"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y" : 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}]}, "error": null} ';


2, cycle resolution and record time

Eval
Copy Code code as follows:

var begintime = new Date ();
for (i = 0; i < count; i++) {
o = eval ("(" + jsonstring +) ");
}
Console.output ("eval:" + (New Date ()-begintime));


New Function
Copy Code code as follows:

var begintime = new Date ();
for (i = 0; i < count; i++) {
o = new Function ("return" + jsonstring) ();
}
Console.output ("New Function:" + (New Date ()-begintime));


Native
Copy Code code as follows:

if (typeof JSON!== "undefined") {
var begintime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (jsonstring); }
Console.output ("Native:" + (New Date ()-begintime));
} else {
Console.output ("Native:not support!");
}

second, the test object

Select the current mainstream browsers (regardless of Maxthon), including IE6, 7, 8,firefox2, 3, 3.1,chrome,opera, and Safari3, 4.

Third, test environment

T9300 CPU + 4G Ram + Windows2003, where IE8 is using vista environment, IE7 in another working machine (2G CPU + 2G RAM + Windows2003), considering the main test browser client performance, the result error should be able to meet Affected

Iv. Test Results

* The smaller the number, the better.

* The green background in the current column has the best presentation performance, the red performance is the worst
1, Firefox2, 3 all at the bottom, IE6 performance than IE7 (may be related to machine inconsistencies), the performance of Chrome and Safari4 far more than other browsers.

2, the performance of the Eval and new functions in different browsers is inconsistent, overall eval is better, but the performance of Firefox new function is one times the eval, in order to better compatible with each browser, We encapsulate the parsing of JSON individually as an object to handle:
Wrapper
Copy Code code as follows:

var __json = null;
if (typeof JSON!== "undefined") {
__json = JSON;
}
var browser = browser;
var JSON = {
Parse:function (text) {
if (__json!== null) {
return __json.parse (text);
}
if (Browser.gecko) {
Return the new Function ("return" + Text) ();
}
Return eval ("(+ text +)")
}
};
var begintime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (jsonstring); }
Console.output ("wrapper:" + (New Date ()-begintime));

After adding the wrapper result:

Because of the overhead involved in calling an object, the encapsulated JSON object is slower than a single call, but it ensures that the most appropriate method is used under each browser.


V. Conclusion

When parsing a JSON string, different browsers choose a different method:

IE6, 7 using eval
IE8 using native JSON objects
Firefox2, 3 using the new Function
Safari4 Use eval
The performance of the eval and new functions is basically the same in other browsers

If there are different opinions welcome to pat the Bricks:)

Update:

2009.03.23: Screen all Firefox add-ons and test again
Because known in Firefox run code is completely inconsistent with the results of the suspect is the Firefox plug-in cause, so the ban on all plug-ins (later indicated almost by Firebug), again in Firefox2, 3 under test, the results are as follows:

This shows that the performance of Firefox itself is not as low as we had previously tested, and the performance is good after removing the plugin. But without the support of a Firebug class of Plug-ins, Firefox has greatly reduced our attractiveness.

2009.03.31: Each time a new JSON string is used in the loop
According to Oliver's description, he speculated that Safari4 and Chrome had cached the eval results, resulting in "virtual" high test results, which proved his theory:

From this result we can see that opera has the best performance, Ie8 second.

The main modified code:

Copy Code code as follows:

eval 2:var begintime = new Date ();
for (i = 0; i < count; i++) {
o = eval ("+" {"value": {"items": [{x]: ' + i + ', "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z" ": 3}, {" X ": 1," Y ": 2," Z ": 3}]}," error ": null} ' +") ";
}
Console.output ("eval:" + (New Date ()-begintime));
New Function
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = new Function ("return" + ' {"value": {"items": [{] x ": ' + i + '," Y ": 2," Z ": 3}, {" X ": 1," Y ": 2," Z ": 3}, {" X ": 1," Y ": 2," Z ": 3}, { "X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}]}, "error": null} ') ();
}
Console.output ("New Function:" + (New Date ()-begintime));
Native
if (typeof JSON!== "undefined") {
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (' {"value ': {" items ": [{" x]: ' + i + ', "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}]}, "error": null} ');
}
Console.output ("Native:" + (New Date ()-begintime));
} else {
Console.output ("Native:not support!");
}
Wrapper
var __json = null;
if (typeof JSON!== "undefined") {
__json = JSON;
}
var browser = browser;
var JSON = {
Parse:function (text) {
if (__json!== null) {
return __json.parse (text);
}
if (Browser.gecko) {
Return the new Function ("return" + Text) ();
}
Return eval ("(+ text +)")
}
};
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (' {"value ': {" items ": [{" x]: ' + i + ', "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}]}, "error": null} ');
}
Console.output ("wrapper:" + (New Date ()-begintime));

Attached: All code
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>parse jsonstring</title>
<body>
<div id= "Consoleregion" ></div>
<script type= "Text/javascript" >
Yui
var Browser = function () {
var o = {
ie:0,
opera:0,
gecko:0,
webkit:0
};
var ua = navigator.useragent, M;
if ((/khtml/). Test (UA)) {
O.webkit = 1;
}
Modern WebKit browsers are at least X-grade
m = Ua.match (/applewebkit\/([^\s]*)/);
if (M&&m[1]) {
O.webkit=parsefloat (m[1]);
}
if (!o.webkit) {//Not WebKit
@todo check opera/8.01 (J2ME/MIDP; Opera mini/2.0.4509/1316; Fi U SSR
M=ua.match (/opera[\s\/] ([^\s]*)/);
if (M&&m[1]) {
O.opera=parsefloat (m[1]);
else {//not opera or WebKit
M=ua.match (/msie\s) ([^;] *)/);
if (M&&m[1]) {
O.ie=parsefloat (m[1]);
else {//not opera, WebKit, or IE
M=ua.match (/gecko\/([^\s]*)/);
if (m) {
O.gecko=1; Gecko detected, look for revision
M=ua.match (/RV: ([^\s\)]*)/);
if (M&&m[1]) {
O.gecko=parsefloat (m[1]);
}
}
}
}
}
return o;
}();
var Console = {
Consoleregion:null,
Getregion:function () {
if (this.consoleregion = = null) {
This.consoleregion = document.getElementById ("consoleregion");
}
return this.consoleregion;
},
Output:function (text) {
This.getregion (). InnerHTML + + "<br/>" + text;
}
};
Test code
var count = 10000, o = null, i = 0, jsonstring = ' {' value ': {"items": [{"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y" : 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}, {"X": 1, "Y": 2, "Z": 3}]}, "error": null} ';
Eval
var begintime = new Date ();
for (i = 0; i < count; i++) {
o = eval ("(" + jsonstring +) ");
}
Console.output ("eval:" + (New Date ()-begintime));
New Function
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = new Function ("return" + jsonstring) ();
}
Console.output ("New Function:" + (New Date ()-begintime));
Native
if (typeof JSON!== "undefined") {
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (jsonstring);
}
Console.output ("Native:" + (New Date ()-begintime));
} else {
Console.output ("Native:not support!");
}
Wrapper
var __json = null;
if (typeof JSON!== "undefined") {
__json = JSON;
}
var browser = browser;
var JSON = {
Parse:function (text) {
if (__json!== null) {
return __json.parse (text);
}
if (Browser.gecko) {
Return the new Function ("return" + Text) ();
}
Return eval ("(+ text +)")
}
};
BeginTime = new Date ();
for (i = 0; i < count; i++) {
o = Json.parse (jsonstring);
}
Console.output ("wrapper:" + (New Date ()-begintime));
alert (O.VALUE.ITEMS[0].Z);
</script>
</body>
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.