한국어
C/C++
 

C switch와 if 중 어느 것이 더 빠른가

makersweb 2017.01.31 00:47 조회 수 : 2935

switch와 if 을 비교해보고 적절하게 사용하는 방법을 알아보자.

 

#include <stdio.h>

int main(void)
{
int a, b, c, d, x = 0;
int result;

a = b = 3;
c = 5;
d = 6;
result = (a * c) + b / d;

if(result == 0)
x = result + 5;
else if(result == 1)
x = result + 10;
else if(result == 2)
x = result + 15;
else if(result == 3)
x = result + 20;
else if(result == 4)
x = result + 25;
else if(result == 5)
x = result + 30;
else
x = 0;

printf("%dn", x);

return 0;
}

 

if문을 역어셈블로 살펴보면 다음의 그림 처럼 else if 마다 비교 연산을 수행하고있다.

ifelseif.png

 

위의 예제 코드를 switch 문으로 표현한 것이다. 

 

#include <stdio.h>

int main(void)
{
int a, b, c, d, x = 0;
int result;

a = b = 3;
c = 5;
d = 6;
result = (a * c) + b / d;

switch(result)
{
case 0:
x = result + 5;
break;
case 1:
x = result + 10;
break;
case 2:
x = result + 15;
break;
case 3:
x = result + 20;
break;
case 4:
x = result + 25;
break;
case 5:
x = result + 30;
break;
default:
x = 0;
break;
}

printf("%dn", x);

return 0;
}

 

다음의 역어셈에서와 같이 최초 5보다 크면 default레이블로 분기되고 그렇지 않으면 result의 값에 따라 지정된 레이블로 점프됨을 알 수 있다.

switch.png

 

인용 및 참고문헌: 임베디드 프로그래밍 c코드 최적화