Home >Web Front-end >JS Tutorial >Which one should I choose between eval and new Function?_Basic knowledge
Without further ado, let’s go directly to the test code
//eval time is: 211
//new Function time is: 251
//eval time is: 384
//new Function time is: 1024
Dear, don’t be impatient. Read on. With these questions, I finally started another test out of curiosity. At this time, I made a dynamic function to let eval and new Function execute respectively. Let’s take a look. See the effect
Copy code
//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.