JavaScript Splice() vs Shift() 속도 차이 궁금해서 구글링

Dorito·2022년 9월 17일
0

기초공사

목록 보기
4/6

https://velog.io/@dorito/2022.8.20-토요일-공부기록 글에서 분리한 문서입니다.

The best way to remove the first element of an array in Javascript — shift() vs splice()

https://medium.com/@erictongs/the-best-way-to-remove-the-first-element-of-an-array-in-javascript-shift-vs-splice-694378a7b416

배열에서 첫번째 항목 제거할 때 무엇이 더 유리한지 궁금해서 구글링해봤다.
자바스크립트에서는 shift(), splice() 가 첫번째 항목을 제거할 수 있다.

  • Shift()
    shift는 아무런 argument를 받지 않는다.
    배열의 첫번째 인자를 반환하고, 배열에서 해당 인자를 삭제한다
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
array.shift();                  // returns 1
console.log(array);             // prints [2, 3, 4, 5, 6, 7, 8, 9]
  • splice(start, deleteCount)
    배열 첫번째 인자를 지우기 위해서 2개의 argument가 필요하다.
    -> splice(0, 1)

중요한건 splice()는 item이 아닌 배열을 반환한다.

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
array.splice(0, 1);             // returns [1]
console.log(array);             // prints [2, 3, 4, 5, 6, 7, 8, 9]

누가 더 빠르냐?

splice()가 shift()보다 88퍼 느리다.

다시 말해서, shift()가 splice() 걸리는 시간의 10퍼센트밖에 되지 않는다.

따라서 shift()를 사용하는 것이 합리적이다.

왜 더 빠를까?

https://262.ecma-international.org/5.1/#sec-15.4.4.9 에 보면 어떻게 동작하는지 나와있다.

  • shift()
    1. Set firstItem to be equal to array[0]
    1. For every subsequent item (array[1], array[2], …) decrease their index by 1. So array[1] becomes array[0], array[2] becomes array[1], etc.
    2. Delete the last element of the array array[length — 1]
    3. Return firstItem
  • splice(0,1)
    1. Create a new array A with the expression new Array()
    1. Set A[0] to be equal to array[0]
    2. For every subsequent item (array[1], array[2], …) decrease their index by 1. So array[1] becomes array[0], array[2] becomes array[1], etc.
    3. Delete the last element of the array array[length — 1]
    4. Return A

여기서 핵심적으로 다른 점은 스텝 1, 2에 있다.
splice에서는 새로운 배열을 만들어서 넣어서 할당시킨다.
이전에 존재하지 않았던 속성 0의 이러한 인스턴스화 및 정의는 상대적으로 계산 비용이 많이 든다.

결론:
If all you need to do is remove the first element, always use shift() because it is much, much quicker. While splice() is a powerful method that can perform tasks like insertion and multiple extractions, it is unsuitable for this task because it instantiates and manipulates an unnecessary array.

0개의 댓글