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

6 comments:

George Entenman said...

http://englishplus.com/grammar/00000243.htm

Unknown said...

Excuse my ignorance but that version or library has the function: (number).times (function)

Nikolay V. Nemshilov said...

@Javier

That's RightJS

http://rightjs.org

Unknown said...

uau it's a cool library (im going to tweet and bookmark it) thanks

Unknown said...

From my testing, call() is faster in Chrome (3%) and (IE 17%), but apply() is faster in Firefox (v2 7%, v3 14%) and Safari (10%)

Nikolay V. Nemshilov said...

I actually had the results from FF, probably version 3.1 or something. Did you restart your browsers before testing?