最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using slice() with or without [end] argument - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Aug 14, 2015 at 11:56 lockedz asked Aug 14, 2015 at 11:43 lockedzlockedz 2436 silver badges15 bronze badges 2
  • 1 There is no real difference, and you can test that in jsperf – adeneo Commented Aug 14, 2015 at 11:49
  • @adeneo will do. Thank you – lockedz Commented Aug 14, 2015 at 11:50
Add a ment  | 

2 Answers 2

Reset to default 5

If you take a look at the implementation https://developer.mozilla/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;
  .....................................
});

This function has linear plexity (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 pared 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.

发布评论

评论列表(0)

  1. 暂无评论