Sunday, July 5, 2009

Call vs. Apply

Today I'm going to tell you an educational story.

var f = function() {};

var test = function(callback) {
var time = new Date();
(10000).times(callback);
console.log(new Date() - time);
};

var test_with_apply = function() {
test(function() {
f.apply(this, [0,1,2,3,4,5,6,7,8,9]);
});
};

var test_with_call = function() {
test(function() {
f.call(this, 0,1,2,3,4,5,6,7,8,9);
});
};

(10).times(test_with_apply);
console.log('--');
(10).times(test_with_call);

The moral

119
122
118
118
128
119
120
119
119
120
--
55
56
55
55
55
55
55
56
56
55