https://velog.io/@dorito/2022.8.20-토요일-공부기록 글에서 분리한 문서입니다.
배열에서 첫번째 항목 제거할 때 무엇이 더 유리한지 궁금해서 구글링해봤다.
자바스크립트에서는 shift()
, splice()
가 첫번째 항목을 제거할 수 있다.
Shift()
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)
중요한건 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()
splice(0,1)
여기서 핵심적으로 다른 점은 스텝 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.