JavaScript로 swap을 구현할 때 두 가지 방법이 자주 사용되는 것으로 보인다.
이 두 방법의 효율성을 비교해 보았다.
# Swap의 두 가지 방법
1. temp 변수를 이용한 swap
let a = 0;
let b = 1;
// swap
let temp = a;
a = b;
b = temp;
console.log(`a = ${a}, b = ${b}`);
// a = 1, b = 0
2. destructuring을 이용한 swap
let a = 0;
let b = 1;
// swap
[a, b] = [b, a];
console.log(`a = ${a}, b = ${b}`);
// a = 1, b = 0
# 효율성 측정
length가 2인 array를 만들고 두 element를 10000번 바꾸는 시간을 측정하였다.
function swapByTemp(arr) {
let temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
function swapByDest(arr) {
[arr[0], arr[1]] = [arr[1], arr[0]];
}
let arr = [0, 1];
console.time('Swap by temporary variable');
for (let i = 0; i < 10000; i += 1) {
swapByTemp(arr);
}
console.timeEnd('Swap by temporary variable');
console.time('Swap by destructuring');
for (let i = 0; i < 10000; i += 1) {
swapByDest(arr);
}
console.timeEnd('Swap by destructuring');
그 결과는 다음과 같다.

temp를 이용한 swap이 훨씬 효율적이다.
간단히 그 이유를 고찰해 보자면,
temp 변수를 선언하는 것보다 destructuring에 이용되는 배열을 선언하는 것이 메모리 할당 등의 이유로 더 오래 걸리기 때문일 것이라고 추측된다.
물론 한 두 번의 swap에 대해서는 전체 프로그램에 미치는 영향이 미미할 것이기에 무슨 방법을 사용하는지가 큰 영향을 주진 않을 테지만, 큰 데이터 sort 시에는 temp 변수를 이용한 swap을 사용하는 것이 좋아 보인다.
728x90
'Algorithms' 카테고리의 다른 글
| Counting Sort (with JavaScript) (0) | 2023.07.14 |
|---|---|
| Merge Sort (with JavaScript) (0) | 2023.07.14 |
| Quick Sort (with JavaScript) (0) | 2023.07.14 |
| Insertion Sort (with JavaScript) (0) | 2023.07.13 |
| Selection Sort (with JavaScript) (0) | 2023.07.13 |