UFO ET IT

if-else, 스위치 또는 맵 기반 컨디셔닝의 성능

ufoet 2020. 12. 1. 20:10
반응형

if-else, 스위치 또는 맵 기반 컨디셔닝의 성능


나는 자바 스크립트에서 조건부 구조체의 다음 구현의 성능에 대해 궁금합니다.

방법 1 :

 if(id==="camelCase"){
    window.location.href = "http://www.thecamelcase.com";
}else if (id==="jsFiddle"){
    window.location.href = "http://jsfiddle.net/";
}else if (id==="cricInfo"){
    window.location.href = "http://cricinfo.com/";
}else if (id==="apple"){
    window.location.href = "http://apple.com/";
}else if (id==="yahoo"){
    window.location.href = "http://yahoo.com/";
}           

방법 2 :

switch (id) {
case 'camelCase':
    window.location.href = "http://www.thecamelcase.com";
    break;
case 'jsFiddle':
    window.location.href = "http://www.jsfiddle.net";
    break;
case 'cricInfo':
    window.location.href = "http://www.cricinfo.com";
    break;
case 'apple':
    window.location.href = "http://www.apple.com";
    break;
case 'yahoo':
    window.location.href = "http://www.yahoo.com";
    break;

}

방법 3

var hrefMap = {
camelCase : "http://www.thecamelcase.com",
jsFiddle: "http://www.jsfiddle.net",
cricInfo: "http://www.cricinfo.com",
apple: "http://www.apple.com",
yahoo: "http://www.yahoo.com"
};
window.location.href = hrefMap[id];

방법 4

window.location.href = {
    camelCase : "http://www.thecamelcase.com",
    jsFiddle: "http://www.jsfiddle.net",
    cricInfo: "http://www.cricinfo.com",
    apple: "http://www.apple.com",
    yahoo: "http://www.yahoo.com"
}[id];

아마도 방법 3과 4는 거의 동일한 성능을 가질 수 있지만 확인을 위해 게시하는 것입니다.


JSBen.ch 테스트 에 따르면 switch설정은 제공된 방법 (Firefox 8.0 및 Chromium 15) 중에서 가장 빠릅니다.

방법 3과 4는 약간 덜 빠르지 만 거의 눈에 띄지 않습니다. 분명히 if-elseif 방법은 상당히 느립니다 (FireFox 8.0).

Chromium 15의 동일한 테스트에서는 이러한 방법 간의 성능에 큰 차이가 없습니다. 사실 if-elseif 방법은 Chrome에서 가장 빠른 방법 인 것 같습니다.

최신 정보

I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.


You can always do a jsPerf test yourself. However, in general a lookup table is the fastest way to access data. That would be (3) in your snippets. Also, switch/case is almost always faster than if-else. So the order for your example would be

(3) -> (4) -> (2) -> (1)


Just thought I'd add this as a possible consideration. I came across this doing research on this very question... http://davidbcalhoun.com/2010/is-hash-faster-than-switch-in-javascript

It takes different engines and browsers into account.

참고URL : https://stackoverflow.com/questions/8624939/performance-of-if-else-switch-or-map-based-conditioning

반응형