7
lorentz
3y

[JS]
Which one do you think is faster? Pushing callbacks to an array and iterating them when they're due, or this:
const oldcb = cb;
cb = () => { someNewStuff(); oldcb(); }
The callbacks can never be removed and will finish fast, their order shouldn't matter.

Comments
  • 3
    It's slightly faster to chain callbacks since you don't need a nested loop, but on my machine it's only about 5ms difference per 120,000 callbacks, so I'd say it's better to keep them in a list since it's easier to comprehend and more readable (plus it gives you better control over errors).
  • 0
    I'd assume the nested callbacks are more performant, but arrays seems much simpler... Alternatively something like the middleware pattern might be an alternative
  • 5
    If their order doesn't matter, why even running them sequentially and not as promises via Promise.all?
  • 0
    @nitwhiz that, I was about to sugest something similar
  • 0
    @nitwhiz Because I don't want to postpone their effects possibly opening myself up to ordering errors and I want to finish synchonously.
    It's basically a bunch of internal destructors for a large but known number of object types that stack up during (asynchronous) operations and that are executed when the result is found. They do comparatively urgent things like removing event handlers so they can't be fired later than the library user would expect.
  • 0
    But there aren't very many of them so I'll probably use an array since it's less confusing.
  • 1
    @homo-lorens oh, i see. So you register them and some event issues them all?
    Definitely array, because readability alone.. nobody wants to debug a callstack hell because callbacks call callbacks.
  • 1
    Premature optimization is the root of all evil.
Add Comment