Skip to content

Instantly share code, notes, and snippets.

@chrisyip
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisyip/9a00edb03a0702750b81 to your computer and use it in GitHub Desktop.
Save chrisyip/9a00edb03a0702750b81 to your computer and use it in GitHub Desktop.
faster array-like slicer, aimed to replace [].slice.call(arguments). jsperf http://jsperf.com/from-slice-vs-slice-call
// https://github.com/lodash/lodash/blob/51e459b386f8301c803442f7fc722e46fc192d35/lodash.js#L2573
// 2 times faster!
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/*
* Author: Chris Yip <i@chrisyip.im>
*/
function slice (arrayLike, startPos, endPos) {
if (!arrayLike) {
return []
}
var result = [],
i = typeof startPos === 'number' || startPos instanceof Number ? startPos : 0,
endIndex = typeof endPos === 'number' || endPos instanceof Number ? endPos : arrayLike.length
if (i < 0) {
i = i + arrayLike.length
if (i < 0) {
i = 0
}
}
if (endIndex < 0) {
endIndex = endIndex + arrayLike.length
if (endIndex < 0) {
endIndex = 0
}
}
if (endIndex > arrayLike.length) {
endIndex = arrayLike.length
}
for (; i < endIndex; i++) {
result[result.length] = arrayLike[i]
}
return result
}
@chrisyip
Copy link
Author

chrisyip commented Oct 7, 2014

node 0.11.14 + benchmark 1.0.0

✓  [].slice.call x 5,772,857 ops/sec ±0.94% (93 runs sampled)
✓  slicer x 13,987,134 ops/sec ±0.83% (95 runs sampled)
✓  lodash.last x 18,485,286 ops/sec ±0.95% (94 runs sampled)
Fastest is lodash.last

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment