Zoldszemesostoros
Zoldszemesostoros

Reputation: 397

Do named event handlers consume more memory than anonymous ones in JavaScript?

Does this code

var list = document.querySelectorAll("div");
for (let i = 0; i < list.length; i++) {
  list[i].addEventListener("event", function (event) {
    /* some code */
  });
}

consume more memory than

var list = document.querySelectorAll("div");
function handler(event) {
  /* some code */
}
for (let i = 0; i < list.length; i++) {
  list[i].addEventListener("event", handler);
}

this?
If I'm not mistaken, the first code stores the event handler for every item in the list, but the second code does it only once. Is that true?

Upvotes: 3

Views: 59

Answers (1)

Barmar
Barmar

Reputation: 782130

It depends.

First of all, all functions have names. In the case of anonymous functions, the name is simply the empty string. So the difference between the two cases is a savings of about 6 bytes, because the name of one function is "handler" while the name of the other is "".

Perhaps what you were wondering is if a new function is created on each iteration of the loop in the first version. That shouldn't be necessary in this case.

This depends on whether the function contains any references to i. If it does, each iteration will need to create a closure that references that iteration's scope of i. There will be just one function, but multiple closures.

However, if the two snippets are intended to be equivalent, handler() can't refer to i. So in this case there should be no need for multiple closures.

Upvotes: 2

Related Questions