Constructing Object With New Function(){} Vs. Invoking Function With (function(){})() - Performance?
Solution 1:
My guess would be that the function constructor form (new function() { }
) would be faster than returning an object literal in a closure ((function(){ return {}; })()
) because the latter seems to be doing a little more work than the former.
However, it appears I am wrong, at least for a couple modern JavaScript engines. This jsPerf comparison shows the literal/closure form to be considerably faster in both Chrome and Firefox.
Ultimately, I think the correctness of the code and the clarity of the intent of the programmer is more important than such a trivial optimization (which likely varies greatly between real-world JavaScript engines anyway).
Solution 2:
It may make the initial creation of the object slower, most likely immeasurably so.
As far as I know it'll make not one iota of difference to the performance of any subsequently executed methods of that object.
Solution 3:
I'm guessing the only advantage to using new
is if you like the syntax of
this.myfunct = function...
If you did that without the new
, you would be polluting the global namespace
but other than that there really is no difference.
If speed bothers you, being that jsperf puts it at one millionth of a second slower, if you're doing one million IIFEs then you're doing something worng
Post a Comment for "Constructing Object With New Function(){} Vs. Invoking Function With (function(){})() - Performance?"