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?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 .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 .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 .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 .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 .Source: https://habr.com/ru/post/55553/
All Articles