Alexander Mills
Alexander Mills

Reputation: 100230

pop() / shift() method which returns original array

I've read that pop()/shift() is significantly more performant than using slice(). https://jsperf.com/pop-vs-slice/5

Here's my use case using slice():

proto.wrapErrorFirst = proto.wrapErrFirst = function (fn: Function) {
  const self = this;
  return function (err: IPseudoError) {
    if (err) {
      return self.__handle(err, false);
    }
    try {
      // remove the error-first argument
      return fn.apply(this, Array.from(arguments).slice(1));
    }
    catch (err) {
      return self.__handle(err, false);
    }
  }
};

so this should be more performant:

  proto.wrapErrorFirst = proto.wrapErrFirst = function (fn: Function) {
      const self = this;
      return function (err: IPseudoError) {
        if (err) {
          return self.__handle(err, false);
        }
        try {
          const args = Array.from(arguments);
          args.shift()
          return fn.apply(this, args);
        }
        catch (err) {
          return self.__handle(err, false);
        }
      }
    };

but I am wondering if there is a way to do that with less code and perhaps a way to do that without having to call Array.from(arguments)?

maybe something kinda crazy like this:

delete arguments[0];
return fn.apply(this, arguments);

Upvotes: 2

Views: 252

Answers (2)

Ilya Rezvov
Ilya Rezvov

Reputation: 944

You create new array from arguments any way, but also you want to skip first element. Most efficient way to do it in your case is using slice method from Array.prototype on arguments. So you do not need create temporary array as in first case and then slice it, and you do not need remove first element as in second case.

proto.wrapErrorFirst = proto.wrapErrFirst = function (fn: Function) {
  const self = this;
  return function (err: IPseudoError) {
    if (err) {
      return self.__handle(err, false);
    }
    try {
      const args = Array.prototype.slice.call(arguments, 1);
      return fn.apply(this, args);
    }
    catch (err) {
      return self.__handle(err, false);
    }
  }
};

Upvotes: 2

Ciro Spaciari
Ciro Spaciari

Reputation: 630

Pop/Shift is the fast way you can use splice or slice, but pop/shift is faster at lest in chrome, delete is not proper for remove elements of an array See more here.

Upvotes: 2

Related Questions