The best way to remove head elements from an array is splice(0,1) VS shift()

Often when removing the first element of an array, I can’t help but wonder which method is better, so I did an in-depth study of the principles of these two methods.

shift() use

Without arguments, removing the first element of an array and returning it modifies the original array.

splice use

Receive three or more parameters, the starting index of the array operation, the number of elements to be deleted and the elements to be added (you can write multiple) will modify the original array

The difference in return values: shift returns the deleted element, splice returns the deleted element and puts it in an array.

specific implementation of shift()

Assign the first item of the array to firstItem, then move the index of subsequent elements forward by one, delete the last element, and finally return firstItem.

Specific implementation of splice(0,1)

Use the new Array() expression to create a new array A(), set A[0] = array[0], then move the subsequent elements of array[0] forward one position, delete the last element, and finally return the array A.

Test Results:

From the data point of view, shift() is more efficient. In terms of implementation, except for the first element, the movement operation of elements is the same. In addition, splice needs to open up an additional space for the array A and assign the first element to A[0]. The calculation cost is greater than that of shift. Although the splice method is very powerful, shift is more efficient for deleting the first element of the array.

Guess you like

Origin blog.csdn.net/Suk__/article/details/129995070