A classmate of mine had a whiteboard challenge as follows: make a function that accepts an array and a number, N. Rotate the values in that array to the left N times. Two solutions were suggested. Use array.push() and array.shift() or use array.slice(). Below are the two code snippets:
function arrayRotationUnshiftPush(array, numberOfRotations) {
for (let i = 0; i < numberOfRotations%array.length; i++) {
array.push(array.shift());
}
return array
}
function arrayRotationSplice(array, numberOfRotations) {
index = numberOfRotations%array.length;
return [...array.splice(index), ...array]
}
To test out which approach is faster, I created a dummy array if integers:
let array = []
for (i = 0; i<20000; i++) {
array[i] = i;
}
Then I called the functions on the array and used Date.now() to record the time before and after:
let time = Date.now();
for (i = 0; i<20; i++) {
arrayRotationUnshiftPush(array, 1500);
}
console.log(Date.now() - time);
The results were surprising. When the array length became very long, splice was significantly faster. When the number of times each function was called became very long, splice was again much faster. Finally, the deeper into the array, the faster splice became compared to shift and push. All of this suggest that invoking a method adds additional runtime on a very small level that when scaled up creates a noticeable difference in run time.
Top comments (0)