Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript V8 optimisation and "leaking arguments"

Tags:

javascript

v8

I read in various places that it's advisable to be careful with the arguments object and that this is ok...

    var i = arguments.length, args = new Array(i);
    while (i--) args[i] = arguments[i];

But, is this ok or not?...

function makeArray (l) {
    var i = l.length, array = new Array(i);
    while (i--) array[i] = l[i];
    return array;
};
//...
//EDIT: put the function on an object to better represent the actual case
var o = {};
o.f = function (callback) {
    var args = makeArray (arguments);
    callback.apply(args[0] = this, args);
};

What is meant by "leaking arguments" and how does it affect optimisation?

I am focused on V8, but I assume it applies to other compilers as well?

to prove it works...

function makeArray (l) {
    var i = l.length, array = new Array(i);
    while (i--) array[i] = l[i];
    return array;
};
//...
//EDIT: put the function on an object to better represent the actual case
var o = {};
o.f = function (callback) {
    var args = makeArray (arguments);
    callback.apply(args[0] = this, args);
};
o.m = "Hello, ";
function test(f, n) {
    alert(this.m + " " + n)
}
o.f(test, "it works...")
like image 891
Cool Blue Avatar asked Dec 25 '22 19:12

Cool Blue


1 Answers

The problem with arguments is same as with local eval and with: they cause aliasing. Aliasing defeats all sorts of optimizations so even if you enabled optimization of these kind of functions you would probably end up just wasting time which is a problem with JITs because the time spent in the compiler is time not spent running code (although some steps in the optimization pipeline can be run in parallel).

Aliasing due to arguments leaking:

function bar(array) {    
    array[0] = 2;
}

function foo(a) {
    a = 1;
    bar(arguments);
    // logs 2 even though a is local variable assigned to 1
    console.log(a);
}
foo(1);

Note that strict mode eliminates this:

function bar(array) {    
    array[0] = 2;
}

function foo(a) {
    "use strict";
    a = 1;
    bar(arguments);
    // logs 1 as it should
    console.log(a);
}
foo(1);

Strict mode however isn't optimized either and I don't know any reasonable explanation except that benchmarks don't use strict mode and strict mode is rarely used. That might change since many es6 features require strict mode, otoh arguments is not needed in es6 so...

like image 173
Esailija Avatar answered Jan 04 '23 23:01

Esailija