2

Is using a self defined constructor function more expensive than an object literal?

var obj = function(){
    this.foo = "bar; 
}; 

The reason why I ask is because, if I declare an object literal as such:

var obj = { foo: bar }; 

I wonder, if behind the scenes it does the same as:

var obj = new Object(); 
obj["foo"] = "bar";  

If that's the case, I'd assume that they're both approximately as expensive, and choosing one over the other would be trivial (for a case like this).

html_programmer
  • 18,126
  • 18
  • 85
  • 158
  • 3
    Worrying about these performance differences is futile. `new Object` is never used. – elclanrs Aug 04 '15 at 19:07
  • @elclanrs Ok cool... it's sometimes the little things I wonder about the most. – html_programmer Aug 04 '15 at 19:08
  • None of your examples *declares* a constructor function, and `Object` is certainly not self-defined. – Bergi Aug 04 '15 at 19:27
  • 1
    `new Object` is much more expensive, as it needs to resolve the `Object` identifier and call a function (you might have overwritten it!). The object literal in contrast is statically optimisable. And, of course, it's much easier to read. And a shorter string of code to transfer and compile. – Bergi Aug 04 '15 at 19:30
  • There's always jsperf, and I believe this is a dupe, so there's probably something there already. – Dave Newton Aug 04 '15 at 19:31
  • Woops indeed, missed that somehow. – html_programmer Aug 04 '15 at 19:39
  • Um, an `obj` function is very different from an `obj` object. Use what you need, not what is more expensive. – Bergi Aug 04 '15 at 19:53

0 Answers0