jQuery.parseJSON and JSON.parse are two functions that perform the same task. If the jQuery library is already loaded, would using jQuery.parseJSON be better than using JSON.parse, in terms of performance?
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
如您所见,如果可用,jQuery 将使用本机 JSON.parse方法,否则它将尝试使用 new Function计算数据,这有点像 eval。