Programing

자바 스크립트 스위치 vs. if… else if ... else

crosscheck 2020. 7. 5. 08:04
반응형

자바 스크립트 스위치 vs. if… else if ... else


나는 몇 가지 질문이 있습니다.

  1. switch명령문과 JavaScript 사이에 JavaScript의 성능 차이 if...else있습니까?
  2. 그렇다면 왜?
  3. 의 동작입니다 switchif...else브라우저에서 다른가? (FireFox, IE, Chrome, Opera, Safari)

이 질문을하는 이유 switch는 Firefox에서 약 1000 대의 사례가 있는 문장 에서 더 나은 성능을 얻는 것 같습니다 .


편집 됨 불행히도 이것은 내 코드가 아닙니다 .Javascript가 컴파일 된 라이브러리에서 서버 측으로 생성되고 있으며 코드에 액세스 할 수 없습니다. 자바 스크립트를 생성하는 메소드를

CreateConditionals(string name, string arrayofvalues, string arrayofActions)

참고 arrayofvalues는 쉼표로 구분 된 목록입니다.

그것이 생산하는 것은

function [name] (value) {
  if (value == [value from array index x]) {
     [action from array index x]
  }
}

참고 : 여기서 [name]= 서버 측 함수에 전달 된 이름

이제 함수의 출력을 TextArea에 삽입하도록 변경하고 함수를 구문 분석하기위한 JavaScript 코드를 작성하여 일련의 case명령문으로 변환했습니다 .

마지막으로 함수를 실행하면 정상적으로 실행되지만 IE와 Firefox에서는 성능이 다릅니다.


일반적인 답변 :

  1. 예, 보통입니다.
  2. 자세한 정보는 여기를 참조하십시오
  3. 예, 각기 다른 JS 처리 엔진이 있기 때문에 아래 사이트에서 테스트를 실행할 때 스위치는 항상 많은 반복에서 if, elseif를 수행했습니다.

시험장


때로는 둘 다 사용하지 않는 것이 좋습니다. 예를 들어, "디스패치"상황에서 Javascript를 사용하면 완전히 다른 방식으로 작업을 수행 할 수 있습니다.

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

객체를 생성하여 다 방향 분기를 설정하면 많은 이점이 있습니다. 기능을 동적으로 추가 및 제거 할 수 있습니다. 데이터에서 디스패치 테이블을 작성할 수 있습니다. 프로그래밍 방식으로 검사 할 수 있습니다. 다른 함수로 핸들러를 빌드 할 수 있습니다.

"case"에 해당하는 함수 호출의 오버 헤드가 추가되었지만 특정 키에 대한 함수를 찾기위한 해시 조회의 이점 (많은 경우)입니다.


사이의 성능 차이 switchif...else if...else이다 작은, 그들은 기본적으로 같은 일을. 차이점을 만들 수있는 차이점 중 하나는 테스트 할 표현식이 switch각에 대해 한 번만 평가된다는 것 if입니다. 표현식을 평가하는 데 비용이 많이 든다면 한 번 수행하는 것이 백 번 수행하는 것보다 빠릅니다.

이러한 명령 (및 모든 스크립트)의 구현 차이는 브라우저마다 약간 다릅니다. 다른 브라우저에서 동일한 코드에 대해 다소 큰 성능 차이를 보는 것이 일반적입니다.

모든 브라우저에서 모든 코드의 성능을 거의 테스트 할 수 없으므로 수행중인 작업에 가장 적합한 코드를 찾고 수행 방식을 최적화하는 대신 작업량을 줄여야합니다.


  1. If there is a difference, it'll never be large enough to be noticed.
  2. N/A
  3. No, they all function identically.

Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.


Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/else has to be implemented with an O(n) procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?


Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)


Pointy's answer suggests the use of an object literal as an alternative to switch or if/else. I like this approach too, but the code in the answer creates a new map object every time the dispatch function is called:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

If map contains a large number of entries, this can create significant overhead. It's better to set up the action map only once and then use the already-created map each time, for example:

var actions = {
    'explode': function() {
        prepExplosive();
        if( flammable() ) issueWarning();
        doExplode();
    },

    'hibernate': function() {
        if( status() == 'sleeping' ) return;
        // ... I can't keep making this stuff up
    },
    // ...
};

function dispatch( name ) {
    var action = actions[name];
    if( action ) action();
}

  1. Workbenching might result some very small differences in some cases but the way of processing is browser dependent anyway so not worth bothering
  2. Because of different ways of processing
  3. You can't call it a browser if the behavior would be different anyhow

It turns out that if-else if generally faster than switch

http://jsperf.com/switch-if-else/46

참고URL : https://stackoverflow.com/questions/2922948/javascript-switch-vs-if-else-if-else

반응형