Kevin Li
Kevin Li

Reputation: 1538

Constructing object with new function(){} vs. invoking function with (function(){})() - Performance?

`new function()` with lower case "f" in JavaScript

My intuition says using the new keyword would be slower. Is there any noticeable benefit to using either method?

Upvotes: 0

Views: 305

Answers (3)

qwertymk
qwertymk

Reputation: 35276

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

Upvotes: 0

maerics
maerics

Reputation: 156434

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).

Upvotes: 1

Alnitak
Alnitak

Reputation: 339816

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.

Upvotes: 1

Related Questions