Call efficiency (null) and call (window)
function sum (a, b, c, d) {
return a+b+c+d;
}
var result = 0;
var start = new Date().getTime();
for (var i = 0; i < 10000000; i++) {
result = sum.call(window, 1,2,3,4); // 2446 ms
//result = sum.call(null, 1,2,3,4); // 260 ms
}
var dur = new Date().getTime() - start;
alert(dur);
In non-strict mode, the code null and undefined will be replaced by the global object (namely, the window object in the browser).
This begs the question, like the code above, why is sum.call (null, 1,2,3,4) so ββmuch faster than sum.call (window, 1,2,3,4)?
source to share
Not just a window scoped call, any scoped call with many members and properties will take longer.
A null call in accordance with ECMA 262 v5, 10.4.3 will cause this function pointer to be bound to the global.
This will shorten the time:
function sum (a, b, c, d) {
return a+b+c+d;
}
var result = 0;
var start = new Date().getTime();
for (var i = 0; i < 10000000; i++) {
result = sum.call({}, 1,2,3,4); //nearly half of the time(1607ms) which null costs(3478ms) for me.
}
var dur = new Date().getTime() - start;
alert(dur);
source to share
sum.call(null, 1,2,3,4);
or sum.call(window, 1,2,3,4);
both are the same ... you get this
as a ref function internally.
sum.call(null, 1,2,3,4);
function sum (a, b, c, d) {
console.log(this); // null in this variable
return a+b+c+d;
}
If you need to use a function ref
within a function then pass the first parameter to .call()
.
As per your question, it sum.call(null, 1,2,3,4);
will be fast, because window
ref is always large size from null
which you passed as a function ref
in the loop
and a more efficient call function would be straight forward like
sum(1,2,3,4)
because it eliminates the reduction of a single global ref object from the function call.
Demo version of speed test
source to share