Comparing: Switch() and If() -
DeathOnaStick - 16.07.2010
Hey everyone. Just wanted to know if there is a difference (according to the speed) between:
and
pawn Код:
switch(x){case 0:print("x=0");}
I know, the differences will be real small, but i wonder which is actually the faster version.
Thanks!
Re: Comparing: Switch() and If() -
Sergei - 16.07.2010
For only one case, I think there's not any difference really. However, for mroe cases switch is definitelly better and easier to use.
Код:
if(x== 0 || x== 1 || x==2)
or
Код:
switch(x)
{
case 0,1,2:
}
You can make speed test yourself if you want.
Re: Comparing: Switch() and If() - WackoX - 16.07.2010
''If'' Is for short things like:
Код:
if(PlayerInfo[playerid][pAdmin] >= 1 && PlayerInfo[playerid][pAdmin] != 8)
''Switch'' Is for long things like:
Код:
switch(PlayerInfo[playerid][pAdmin])
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
}
Re: Comparing: Switch() and If() -
DeathOnaStick - 16.07.2010
I made some sort of speed test and in this case the if-statement is about 75% faster than the switchfunction.
The if-statement takes about 125ms for 1000 simple operations.
The switchfunction takes 229ms for the same amount of the same operations.
I dont know if 1000 is a good value but i let it run about 10 times now and the results did not change more than 25ms.
Cheers.
#edit#
If you care: here my code:
pawn Код:
main()
{
new TC1, TC2, TC3, TC4, x=0;
TC1=GetTickCount();
for(new i=0; i<=1000; i++)switch(x){case 0:print("x=0");}
TC2=GetTickCount();
TC3=GetTickCount();
for(new i=0; i<=1000; i++)if(x==0)print("x=0");
TC4=GetTickCount();
printf("%d = switchfunction", (TC2-TC1));
printf("%d = if-statement", (TC4-TC3));
}
Re: Comparing: Switch() and If() -
Finn - 16.07.2010
How come for me it looks like
switch is faster when it's about multiple statements and for single statement they're both the same speed?
pawn Код:
new x = 1;
new check1 = GetTickCount();
for(new i; i < 1000; i++)
{
if(x == 0) x = 1;
else if(x == 1) print("abc");
else if(x == 2) x = 1;
else if(x == 3) x = 1;
else if(x == 4) x = 1;
}
new check2 = GetTickCount();
for(new i; i < 1000; i++)
{
switch(x)
{
case 0: x = 1;
case 1: print("abc");
case 2: x = 1;
case 3: x = 1;
case 4: x = 1;
}
}
new check3 = GetTickCount();
for(new i; i < 1000; i++)
{
if(x == 1) print("abc");
}
new check4 = GetTickCount();
for(new i; i < 1000; i++)
{
switch(x)
{
case 1: print("abc");
}
}
new check5 = GetTickCount();
printf("1: %d, 2: %d, 3: %d, 4: %d", check2-check1, check3-check2, check4-check3, check5-check4);
Here's my results with the code above:
Код:
[21:05:52] 1: 227, 2: 103, 3: 102, 4: 101
_______________
I use them both. There's no difference really, only in the indentation.
Re: Comparing: Switch() and If() -
DeathOnaStick - 16.07.2010
I think you're right but my calculation is a bit weird then, because i tried this code very often and i actually dont see a mistake in it?! Anyway, thanks, my question is answered =).