📜 ⬆️ ⬇️

Comparison of browser performance when processing JSON strings

image We parse the JSON string into the JSON object when we process the AJAX responses of the server. Usually, we use eval or new Function to parse JSON strings, however IE8 and Firefox3.1 have built-in JSON support (inline parsing works much faster). How to determine in practice the choice between these three methods? And how to find out whose performance is faster among such a large number of browsers?

Translator's note: here is a partial adapted translation, due to the fact that an update was made in the original, which I cited as the main result.

Code and Terms


Define the json string:
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}' ;

* This source code was highlighted with Source Code Highlighter .


Parsing json strings and recording results:
')
eval

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


* This source code was highlighted with Source Code Highlighter .


new function

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


* This source code was highlighted with Source Code Highlighter .


native

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!" );
}


* This source code was highlighted with Source Code Highlighter .


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 + ")" )
}
};

var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString ); }
Console.output( "wrapper:" + ( new Date() - beginTime ) );


* This source code was highlighted with Source Code Highlighter .

Browsers


IE6, 7, 8; Firefox2, 3, 3.1; Chrome Opera and Safari3, 4.

Test system


T9300 CPU + 4G RAM + Windows2003, IE8 in Vista, IE7 on another machine (2G CPU + 2G RAM + Windows2003)

Test results




Progg it

Source: https://habr.com/ru/post/55553/


All Articles