Javascript function vs new function

According to this standard http://jsperf.com/function-vs-function, the created functions are executed approximately 1000 times faster. Can you comment on this?

+4
source share
2 answers
  • You call f1 , but not f2 . That is, your second test does nothing but search for a link.
  • All work is really done as a setup for the test.

I think you actually are: http://jsperf.com/function-vs-function/2 Update: The second time you may not like this. But, nevertheless, your second test does nothing. You are missing () after f2 ;)

Thus, in addition, new Function works more slowly, it is also more difficult to maintain the body of the function;)

+5
source

with new Function -syntax, a JS compiler must be launched for each function to "eval" the function body string - this is slow and should be avoided when possible:

Each time [...] the Function constructor is called on a line representing the source code, the script engine must start a mechanism that converts the source code of the executable code. This is usually expensive for performance — easily a hundred times more expensive than a simple function call for an example. (Mark Tarquin Wilton-Jones)

if you used a search in StackOverflow, you would find this question that gives very good and detailed information about it.

EDIT: as Martin said in one of the comments below, sometimes the new Function constructor is a wonderful thing. to list some examples:

but: in 99% of cases when you could use new Function , this is a bad idea, which means: just define any function that should be as it is and does not have a kind of “dynamic behavior”, you should always use "normal" functional syntax to speed up your code and avoid eval -like new Function .

+2
source

Source: https://habr.com/ru/post/1336287/


All Articles