JSON文字列を処理するときのブラウザーのパフォーマンスの比較

画像 サーバーのAJAX応答を処理するときに、JSON文字列をJSONオブジェクトに解析します。 通常、JSON文字列の解析にはevalまたは新しいFunctionを使用しますが、IE8とFirefox3.1にはJSONサポートが組み込まれています(組み込み解析ははるかに高速に動作します)。 これら3つの方法の選択を実際に決定する方法は? そして、非常に多くのブラウザの中で誰がパフォーマンスが速いのかをどのようにして知るのですか?



翻訳者のメモ:これは、元の更新が実行されたという事実による部分的に適合した翻訳です。これを主な結果として引用しました。



コードと条件



JSON文字列を定義します。

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 .








JSON文字列の解析と結果の書き込み:



評価する


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 .






ブラウザ



IE6、7、8; Firefox2、3、3.1; クロム OperaおよびSafari3、4。



試験システム



T9300 CPU + 4G RAM + Windows2003、VistaのIE8、別のマシンのIE7(2G CPU + 2G RAM + Windows2003)



試験結果











プログイット




All Articles