找到你要的答案

Q:Using slice() with or without [end] argument

Q:使用slice()或无[结束]的说法

Is there any performance difference using the slice() method with or without the last argument [end]?

Example:

var m = ['But', 'Will', 'It', 'Blend', 'Question'];
var r = m.slice(1,3);

OR

var r = m.slice(2);

PS: not the result as it is, but the performance issue only.

有性能的差异,使用slice()法或无最后辩论[结束]?

例子:

var m = ['But', 'Will', 'It', 'Blend', 'Question'];
var r = m.slice(1,3);

var r = m.slice(2);

PS:不是因为结果,而是性能问题而已。

answer1: 回答1:

If you take a look at the implementation https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice you will see that if the second argument is not sent then it uses the array length so no, I think they are the same.

Array.prototype.slice = function(begin, end) {
  // IE < 9 gets unhappy with an undefined end argument
  end = (typeof end !== 'undefined') ? end : this.length;
  .....................................
});

如果你在执行https://developer.mozilla.org/en/docs/web/javascript/reference/global_objects/array/slice一看你会看到,如果第二个参数不发送然后使用数组的长度,不,我认为他们是相同的。

Array.prototype.slice = function(begin, end) {
  // IE < 9 gets unhappy with an undefined end argument
  end = (typeof end !== 'undefined') ? end : this.length;
  .....................................
});
answer2: 回答2:

This function has linear complexity (O(n)) in both cases, be it with only one parameter specified, or two. It's the first thing to consider.

The second thing is, in case only one parameter specified, the second one (end of the slice) is being calculated under the hood by default value (#length). So you may think of #slice(4) call as of #slice(4, #length), and these two will be the same.

Next, when the interpreter takes this call and builds an AST around it, it has to deal with two values, not one. So it may seem like twice as time consuming. But compared to the whole script, this overhead is totally negligible.

So, there's no significant difference in timing between the two. It's purely the question of readability of the code.

此函数具有线性复杂度(O(n))在这两种情况下,它只有一个参数指定,或两个。这是第一件要考虑的事情。

其次,如果只有一个参数指定的,第二个(底片)计算得到的是引擎盖下的默认值(#长度)。所以你可能会觉得#片(4)称之为#片(4,#长度),这两个都是一样的。

其次,当解释器需要呼叫建立AST在它的周围,它必须处理两个值,而不是一个。所以它看起来可能是耗时的两倍。但与整个脚本相比,这个开销是完全可以忽略不计的。

所以,两者之间的时间没有显著差异。这纯粹是代码可读性的问题。

javascript  slice