Reputation: 35900
Is there a significant performance difference between binding multiple $(window).on('scroll', fn)
s vs combing all of the logic into one event handler?
My code is better organized with just one event handler but I'd like to get the fastest performance out of this particular module. In this use-case there might be 10~100 handlers attached to the scroll event.
Upvotes: 4
Views: 1492
Reputation: 35900
I modified AlliterativeAlice's code after considering Bergi's comment. Using the native scroll event in Chrome I didn't see any significant difference in speed between the two approaches. Run the code below by copy and pasting into the JavaScript console of this web page, what results to you get?...
function log() {
console.log(Array.prototype.join.call(arguments, ' '))
}
var count100 = 0;
var count1 = 0;
function test100() {
$(window).off('scroll');
for (var i = 0; i < 100; i++) {
$(window).on('scroll', function() {
count100++;
});
}
var startTime = performance.now();
for (var x = 0; x < 100; x++) {
window.scroll(0, 0);
for (var j = 0; j < 100; j++) {
window.scroll(0, j + 1);
}
}
var endTime = performance.now();
log("100 handlers: ", endTime - startTime);
}
function test1() {
var count = 0;
$(window).off('scroll');
var fns = [];
for (var i = 0; i < 100; i++) {
fns.push(function() {
count1++;
});
}
$(window).on('scroll', function() {
fns.forEach(function(f) {
f();
})
});
var startTime = performance.now();
for (var x = 0; x < 100; x++) {
window.scroll(0, 0);
for (var j = 0; j < 100; j++) {
window.scroll(0, j + 1);
}
}
var endTime = performance.now();
log("1 handler: ", endTime - startTime);
}
var testCount = 0;
var numberOfRuns = 20;
function logCount() {
console.log("-->count1: ", count1);
console.log("-->count100: ", count100);
}
function runTestA() {
test1();
if (++testCount<numberOfRuns) setTimeout(runTestB, 10);
else setTimeout(logCount, 10);
}
function runTestB() {
test100();
if (++testCount<numberOfRuns) setTimeout(runTestA, 10);
else setTimeout(logCount, 10);
}
runTestA();
Upvotes: 2