ホームページ  >  記事  >  ウェブフロントエンド  >  evalとnew​​ Functionどっちを選べばいいの?_基礎知識

evalとnew​​ Functionどっちを選べばいいの?_基礎知識

WBOY
WBOYオリジナル
2016-05-16 17:36:531024ブラウズ

早速、テスト コードに直接進みましょう

コードをコピーします コードは次のとおりです次のように:

var aa = "{name:'コーラ',item:[{age:11},{age:22},{age:23},{age:23}] }";
var now = new Date().getTime();
for (var i = 0; i var a = eval("(" aa ") ");

}
var now1 = new Date().getTime();
document.write("評価時間は:" (now1 - now) "
");


var now2 = new Date().getTime();
for (var i = 0; i var fn = new Function ("return" aa) ;
fn(); ");


//テスト後のFF効果は以下の通りです
// IE8 のテスト結果の影響は次のとおりです。
// 評価時間: 913
// 新しい関数時間: 1037
//Chrome のテスト結果は次のとおりです

//評価時間: 211
//new 関数時間: 251

//テスト結果 Opera

//評価時間: 384
//新しい関数時間: 1024

テスト結果は、さまざまなブラウザーのテストの参照データです。なぜすべてのブラウザーのテストがそれを使用する必要があるのか​​ということです。


皆さん、焦らないでください。これらの質問を踏まえて、私はついに eval と new Function を実行するための動的関数を作成しました。効果を参照してください

コードをコピー

コードは次のとおりです。var testEval = function (obj ) { > };
var testFun = function (obj) {
var fn = new Function("return " obj); 🎜>
var now = new Date().getTime();
for (var i = 0; i var fn = testEval("function test(){ document .write('決して乗らない小さなロバがいます...') }");
;
document.write("
"); ("評価時間は:" (now1 - now) "
");

var now2 = new Date().getTime();
for (var i = 0; i var now2 = new Date().getTime(); どちらにも乗らないでください...');");
}
var now3 = new Date( ).getTime();
document.write("new 関数の時刻は次のとおりです: " (now3 - now2) "
");


//After testing, the FF effect is as follows
//eval time is: 495
//new Function time is: 50

//The test results of IE8 are as follows
//Eval time is: 34
//New Function time is: 20

//The test results of Chrome are as follows
//eval time is: 7
//new Function time is: 4

//Test results Opera
//eval time is: 7
//new Function time is: 18

The above results test is super slow to execute EVAL on FF. Other browsers are not much different. We don't have to investigate too much here. ); Maybe you think what this 0 here means. Adding 0 is mainly to be compatible with all browsers. If you don’t add it, versions below IE9 will report an error
But I really don’t know how to analyze the real meaning of 0. I just know that adding this can solve the disgusting IE incompatibility problem
The above two chestnuts show that if it is for the conversion of JSON strings, eval is obviously faster, and if it is dynamic function analysis, then new Function is faster, here is what it says There are two advantages and disadvantages. The other is that eval compatibility is not very good. If there is an error in parsing, other JS scripts may not be executed.
But the latter will not, it will only target this Function me This person doesn't like things that are too troublesome, so he decisively abandons eval and uses new Function instead. If there is anything I don’t understand correctly, please correct me. Comments are welcome.

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。