My code involves lots of event handlers, which do not require any context (scope) to execute. When I use inline lambda functions in contrast to statically declared (constant) lambda functions, a new event handler is created each time I assign the event handler.
Question: Is it possible to define an inline lambda function, which does not create a new Function
object for each time the lambda is passed as a callback. (Given that no unique context scope is required.)
Two examples illustrating the trade-off between notation and memory usage.
1. Inline lambda: (desired notation, unnecesarry memory consumption)
for (const divId of ["div1", "div2", "div3"]) {
documentgetElementById(divId).addEventListener("click", e => console.log(e));
} // Creates a new Function
// object for each loop
// cycle.
Desired notation, but creates a new Function
callback (e => console.log(e)
) for each divId
, despite the callback not depending on any context information (hence being functionally equivalent for each divId
). It would be great if there was a way to just pass a pointer to this function.
2. Statically declared lambda: (undesired notation, desired and minimal memory consumption)
const staticLambda = e => console.log(e); // Function object created only once.
for (const divId of ["div1", "div2", "div3"]) {
documentgetElementById(divId).addEventListener("click", staticLambda);
}
Undesired notation (needs the extra constant), but on the up-side only creates the Function
callback (staticLambda
) once for all three divIds
.
Imagine how this would look inside a class method; the lambda function needs to be declared outside of its respective method as a static property of the class, hence destroying the elegance of lambdas (which are so good at keeping the callback code at the location where it is passed).
Note: This is a simplified example. I realize that creating 2 (out of 3) unnecessary callbacks does not affect performance substantially, however, I am interested in properly handling cases with orders of magnitude more callbacks.