Backbone.js internal triggerEvents function. How is it optimized?

I was reading the Backbone source code and I came across the triggerEvents function that is used internally. The feature includes the comment "Invalid but optimized internal send function". I was curious if anyone with a better understanding of the inner mechanics of JavaScript could explain how this is optimized. Function along with comment

// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
  var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
  switch (args.length) {
    case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
    case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
    case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
    case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
    default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
   }
};

      

+3


source to share


1 answer


Function.prototype.apply

is essentially the same as Function.prototype.call

, with a little more logic, which splits the argument array into separate arguments. By using call

explicitly instead apply

, this way is a bit optimized because it only goes through this extra logic if there are more than 3 arguments.

See: Calling ECMAScript 5 to Apply BOM



In any case, in ECMAScript 6, both functions will have a tail call optimization that essentially "rewires" the function instead of making an additional call to the same function.

call ECMAScrip 6 and apply the spec

+4


source







All Articles