Search code examples
javascriptv8ecmascript-5javascript-engine

Why is new slow?


The benchmark:

JsPerf

The invariants:

var f = function() { };

var g = function() { return this; }

The tests:

Below in order of expected speed

  • new f;
  • g.call(Object.create(Object.prototype));
  • new (function() { })
  • (function() { return this; }).call(Object.create(Object.prototype));

Actual speed :

  1. new f;
  2. g.call(Object.create(Object.prototype));
  3. (function() { return this; }).call(Object.create(Object.prototype));
  4. new (function() { })

The question:

  1. When you swap f and g for inline anonymous functions. Why is the new (test 4.) test slower?

Update:

What specifically causes the new to be slower when f and g are inlined.

I'm interested in references to the ES5 specification or references to JagerMonkey or V8 source code. (Feel free to link JSC and Carakan source code too. Oh and the IE team can leak Chakra source if they want to).

If you link any JS engine source, please explain it.


Solution

  • The problem is that you can inspect the current source code of various engines, but it won't help you much. Don't try to outsmart the compiler. They'll try to optimize for the most common usage anyway. I don't think (function() { return this; }).call(Object.create(Object.prototype)) called 1,000 times has a real use-case at all.

    "Programs should be written for people to read, and only incidentally for machines to execute."

    Abelson & Sussman, SICP, preface to the first edition