Javascript Performance(2)

표인수·2021년 5월 13일
0

Switch, if, ifelse 세가지 조건문의 성능 비교

1. Switch

function Test(input) {
    switch (input) {
        case 1: return 1;
        case 2: return 2;
        case 3: return 3;
        case 4: return 4;
        case 5: return 5;
        case 6: return 6;
        case 7: return 7;
    }
}

const Timer = Date.now();
for (let i = 0; i < 1000000000; i++) {
    Test(i%7+1);
}
console.log(Date.now()-Timer); // 2102

2. if

function Test(input) {
    if (input == 1) return 1;
    if (input == 2) return 2;
    if (input == 3) return 3;
    if (input == 4) return 4;
    if (input == 5) return 5;
    if (input == 6) return 6;
    if (input == 7) return 7;
}

const Timer = Date.now();
for (let i = 0; i < 1000000000; i++) {
    Test(i%7+1);
}
console.log(Date.now()-Timer); // 2102

3. ifelse (slowest)

function Test(input) {
    if (input == 1) return 1;
    else if (input == 2) return 2;
    else if (input == 3) return 3;
    else if (input == 4) return 4;
    else if (input == 5) return 5;
    else if (input == 6) return 6;
    if (input == 7) return 7;
}

const Timer = Date.now();
for (let i = 0; i < 1000000000; i++) {
    Test(i%7+1);
}
console.log(Date.now()-Timer); // 2117

결론

위의 두 문법은 실행 결과가 같았지만, if else 문법만 약간의 성능 저하가 있었다

0개의 댓글