if-else가 아닌 switch 문이 필요한 이유는 무엇입니까?
나는 이것을 한동안 궁금해하고 있습니다. 저는 하드 코어 프로그래머, 주로 작은 Python 스크립트가 아니며 분자 역학 시뮬레이션을 몇 개 작성했습니다. 실제 질문 : switch 문의 요점은 무엇입니까 ? 왜 그냥 if-else 문을 사용할 수 없습니까?
귀하의 답변에 감사 드리며 이전에이 질문이 있었다면 저에게 링크를 알려주십시오.
편집하다
S.Lott 는 이것이 If / Else vs. Switch 질문의 중복 일 수 있다고 지적했습니다 . 닫으려면 그렇게하십시오. 추가 논의를 위해 열어 두겠습니다.
스위치 구조는 더 쉽게로 번역 점프 (또는 지점) 테이블 . 이것은 case 레이블이 서로 가까이있을 때 if-else 보다 switch 문을 훨씬 더 효율적으로 만들 수 있습니다 . 아이디어는 일련의 점프 명령을 메모리에 순차적으로 배치 한 다음 값을 프로그램 카운터에 추가하는 것입니다. 이렇게하면 일련의 비교 명령이 추가 작업으로 바뀝니다.
다음은 매우 단순화 된 의사 조립 예제입니다. 먼저 if-else 버전 :
// C version
if (1 == value)
function1();
else if (2 == value)
function2();
else if (3 == value)
function3();
// assembly version
compare value, 1
jump if zero label1
compare value, 2
jump if zero label2
compare value, 3
jump if zero label3
label1:
call function1
label2:
call function2
label3:
call function3
다음은 스위치 버전입니다.
// C version
switch (value) {
case 1: function1(); break;
case 2: function2(); break;
case 3: function3(); break;
}
// assembly version
add program_counter, value
call function1
call function2
call function3
결과 어셈블리 코드가 훨씬 더 간결하다는 것을 알 수 있습니다. 값은 1, 2 및 3이 아닌 다른 값을 처리하기 위해 어떤 방식 으로든 변환되어야합니다. 그러나 이것은 개념을 설명해야합니다.
Switch can be optimized by compiler - you will get faster code.
Also I find it to be more elegant when dealing with enumerable types.
To sum up switch statement gives you performance + code elegance :)
Here are some useful links:
- speed comparison of switch vs if/else in C#
- Feedback-Guided Switch Statement Optimization (pdf describing switch statement optimization)
For expressiveness, the switch/case statement allows you to group multiple cases together, for example:
case 1,2,3: do(this); break;
case 4,5,6: do(that); break;
For performance, compilers can sometimes optimize switch statements into jump tables.
I'm ignoring this type of low level optimization as usually unimportant, and probably different from compiler to compiler.
I'd say the main difference is readability. if/else is very flexible, but when you see a switch you know right away that all of the tests are against the same expression.
Besides the other mentioned Code readability and optimisation in .NET you also get the ability to switch on enums etc
enum Color { Red, Green, Blue };
Color c = Color.Red;
switch (c) // Switch on the enum
{
// no casting and no need to understand what int value it is
case Color.Red: break;
case Color.Green: break;
case Color.Blue: break;
}
The ability to fall through several cases (intentionally leaving out the break statement) can be useful, and as a few people have already said it's faster as well. Perhaps the most important and least important consideration though, is that it just makes for prettier code than if/else. :)
Switch can be optimized "Better" by some compilers. There are pitfalls with using the switch statement in certain languages. In Java, the switch cannot handle strings and in VB2005 the switch statement will not work with radio buttons.
Switch can be faster and easier to read, If-Then is more generic and will work in more places.
The only time switches can be faster are when your case values are constants, not dynamic or otherwise derived, and when the number of cases is significantly larger than the time to calculate a hash into a lookup table.
Case in point for Javascript, which compiles to assembly for execution on most engines, including Chrome's V8 engine, is that switch statements are 30%-60% slower to execute in the common case: http://jsperf.com/switch-if-else/20
참고URL : https://stackoverflow.com/questions/449273/why-the-switch-statement-and-not-if-else
'Development Tip' 카테고리의 다른 글
PHP에서 로그 파일을 만드는 방법은 무엇입니까? (0) | 2020.12.07 |
---|---|
Elastic Beanstalk T2 서버는 내 node.js 앱 파일을 어디에 저장하나요? (0) | 2020.12.07 |
가장 가까운 달러로 반올림 된 통화를 더블로 포맷하려면 어떻게합니까? (0) | 2020.12.07 |
Linux에서 메일 명령을 사용하여 파일을 첨부하는 방법은 무엇입니까? (0) | 2020.12.07 |
부울 값 전환 / 반전 (0) | 2020.12.07 |