Performance Comparison and Analysis code for parsing Json strings using JavaScript

Source: Internet
Author: User

The method used for parsing is generally eval or new function. Currently, IE8 and Firefox3.1 have built-in native JSON objects (it is said that there will be a certain performance improvement ). In actual use, how can we choose from these three methods (because of performance problems, do not consider using javascript to implement parsing? In the face of a large number of browsers, which method of performance is the best?

I. Test Methods

1. specify the number of tests and the JSON string.

Copy codeThe Code is 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. cyclically parse and record the time

EvalCopy codeThe Code is as follows: var beginTime = new Date ();
For (I = 0; I <count; I ++ ){
O = eval ("(" + jsonString + ")");
}
Console. output ("eval:" + (new Date ()-beginTime ));

New FunctionCopy codeThe Code is as follows: var beginTime = new Date ();
For (I = 0; I <count; I ++ ){
O = new Function ("return" + jsonString )();
}
Console. output ("new Function:" + (new Date ()-beginTime ));

NativeCopy codeThe Code is 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! ");
}

Ii. Test Object

Select mainstream browsers (excluding the shell of Maxthon), including IE6, 7, 8, Firefox2, 3, 3.1, Chrome, Opera, Safari3, and 4.

Iii. Test Environment

T9300 CPU + 4g ram + Windows2003, IE8 uses the Vista environment, IE7 is on another working machine (2g cpu + 2g ram + Windows2003 ), considering that the main purpose is to test the performance of the browser client, the error of the result should be acceptable.

Iv. Test Results

* The smaller the value, the better.

* In the current column, the green background indicates the best performance, and the red background indicates the worst performance.
1. Firefox2 and 3 are all at the bottom. The performance of IE6 is superior to that of IE7 (may be related to machine inconsistencies). Chrome and Safari4 have far higher performance than other browsers.

2. The performance of eval and new functions in different browsers is inconsistent. In general, eval is better, but the performance of new functions in Firefox is twice that of eval. In order to better be compatible with various browsers, we encapsulate JSON parsing into an object for processing:
WrapperCopy codeThe Code is 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 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 ));

Result After adding Wrapper:

Because of the overhead of the called object, the encapsulated JSON object will be slower than a separate call, but it can ensure that the most suitable method is used in various browsers.

V. Conclusion

When parsing a Json string, different browsers choose different methods:

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

If you have different opinions, please click here :)

Update:

2009.03.23: Disable Add-Ons of all Firefox before testing.
Known runs the code in Firefox and returns completely inconsistent results. It is suspected that it is caused by the Firefox plug-in. Therefore, after all the plug-ins are disabled (it was later indicated that it was caused by Firebug ), tested again in Firefox2 and 3, and the results are as follows:

This shows that Firefox's performance is not as low as we tested previously, and the performance is still good after the plug-in is removed. But Firefox has no support for plug-ins such as Firebug, and its appeal to us is also greatly reduced.

2009.03.31: The New json string is used each time in the loop.
According to Oliver's description, he guessed that Safari4 and Chrome cached eval results, resulting in high false scores. The test results proved his speculation:

From this result, we can see that Opera has the best performance, followed by ie8.

Main modified code:

Copy codeThe Code is 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 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 ));

Appendix: all codesCopy codeThe Code is as follows: <! Doctype html public "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Parse JsonString </title>
</Head>
<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 (j2_midp; Opera Mini/2.0.20.9/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
Varcount = 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 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>
</Html>

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.