开发者

javascript function vs new Function

According to this benchmark http://jsperf.com/function-vs-function created functions run about 1000 times fas开发者_如何学Pythonter. Can you comment this?


  1. You are calling f1 but not f2. I.e. your second test is doing nothing but looking up a reference.
  2. All the work is actually done as setup for the test.

I think what you want is actually this: http://jsperf.com/function-vs-function/2 Update: On second thought, you might not want this. But nevertheless, your second test is doing nothing. You are missing the () after f2 ;)

So besides new Function being way slower, it is also harder to maintain the body of the function ;)


with the new Function-syntax, for every function the JS-compiler has to be started to "eval" the function body string - this is slow and should be avoided when possible:

Each time […] the Function constructor is called on a string representing source code, the script engine must start the machinery that converts the source code to executable code. This is usually expensive for performance – easily a hundred times more expensive than a simple function call, for example. (Mark ‘Tarquin’ Wilton-Jones)

if you had used the search on StackOverflow, you would have found this question wich give very good and detailed information about that.

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

  • John Resigs Micro-Templating Engine
  • This piece of code from another Question an SO
  • to be continued...

but: in 99% of the cases where you could use new Function, it's a bad idea - wich means: to simply define any function that has to be like it is and doesn't have some kind of "dynamic bahavior", you should always use the "normal" function-syntax to speed up your code and avoid the eval-like functionality of new Function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜