0

`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?

Community
  • 1
  • 1
Kevin Li
  • 1,540
  • 2
  • 17
  • 23

3 Answers3

1

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • +1 for the "no difference" comment. With the (function() {})() method, more than likely you will create an empty object within the closure, so it may or may not be slower, but there would be a lot of other places you can optimize before needing the performance diff of one of these two approaches. – vhallac Jun 22 '11 at 13:00
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).

maerics
  • 151,642
  • 46
  • 269
  • 291
  • That comparison is not fair. [`Benchmark`](http://jsperf.com/new-function-vs-literal-in-closure/3) is more fair. – Raynos Jun 22 '11 at 13:15
  • @Raynos: true, there are some subtle differences between the forms that OP is comparing (the returned object prototypes differ in both of our benchmarks) but my intent was to compare them exactly as he asks, as they would be used in the real-world. – maerics Jun 22 '11 at 13:21
  • [Better benchmark](http://jsperf.com/new-function-vs-literal-in-closure/5). `new` is faster if it's static. – Raynos Jun 22 '11 at 13:23
0

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

qwertymk
  • 34,200
  • 28
  • 121
  • 184