How to manage arguments

Apologies in advance if I am using the search engine too poorly and this has already been answered. In this case, point me in the right direction.

I recently started using the arguments variable in functions and now I need to cut it off. Wherever I look, people do things like:

function getArguments(args, start) {
    return Array.prototype.slice.call(args, start);
}

      

And according to MDN, this is bad for performance:

You shouldn't slice up the arguments because it prevents optimization in JavaScript machines (like V8).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Is there any reason why I can't see anyone doing things like this:

function getArguments(args, start) {
    var i, p = 0;
    var len = args.length;
    var params = [];

    for (i = start; i < len; ++i) {
        params[p] = args[i];
        p += 1;
    }

    return params;
}

      

You get the arguments you want and the slicing fails. So from my point of view, you are not losing anything in this, perhaps it uses a little extra memory and is a little slower, but not to the point where it really matters, right?

Just wanted to know if my logic is wrong.

+3


source to share


2 answers


Here to discuss

and here's an introduction



eg. here uses inline slice

0


source


From the discussion, it can be seen that @Eason posted ( here ) that the debate is in the category of "micro-optimization", that is: most of the time we will never encounter these performance errors, because our code does not run through the iterations that are necessary to even appear on the radar.

Here's a nice quote that summarizes it:



Micro-optimizations like this will always be a trade-off between code complexity / readability and performance.

In many cases, complexity / readability is more important. In this case, a very slow method which was tested by the 4.3 microsecond runtime network. If you are writing a web service and you slice the arguments twice per request and then do 100ms of other work, the additional 0.0086ms won't be noticeable, and it's not worth the time or code pollution to optimize.

These optimizations are most useful in really hot loops that you hit a gajillionty times. Use a profiler to find your hottest code and optimize your hottest code first until the performance you achieve is satisfactory.

I am happy and will use Array.prototype.slice.call()

unless I find a performance scrolling that indicates that a particular piece of code is not getting into the V8 optimizer.

0


source







All Articles