According to this benchmark http://jsperf.com/function-vs-function created functions run about 1000 times faster. Can you comment this?
2 Answers
- You are calling
f1but notf2. I.e. your second test is doing nothing but looking up a reference. - 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 ;)
Comments
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.
8 Comments
function(){} and "75,310 / 99% slower" for new Function - don't know what you're talking about.function(){}-syntax", the new Function-syntax is a bad idea. i agree with you that in special cases it's a really great possibility.
console.loghere anyways :)