As a general rule the fewer decisions that have to be made at run time the more efficent the script is.
Since the switch statment compiles just about the same as the if.. else if.. statments, There is normally no real gain in efficiency in using one over the other. In breaking up the cases you can limit the maximum number of decisions the script could possibly make at run time.
as an example with your 40 case switch. Cases 0 through 39.
int x = random(40);
switch (x)
{
case 0:
case 1:
case 2:
...
case 39:
default :
}
With the code above 1 to 39 comparisons will be made every time the switch is ran.
If x = 0; only 1 comparision is made.
if x= 39; 40 comparisons are made.
if x is not in the {0..39} set, all 40 comparisons are still made and the defualt is then ran.
Now take the following code.
int x = random(40);
int y = x/10;
switch (y)
{
case 0:
switch(x)
{
case 0:
case 2:
...
case 9:
}
break;
case 1:
switch(x)
{
case 10:
case 12:
...
case 19:
}
break;
case 2:
switch(x)
{
case 20:
case 22:
...
case 29:
}
break;
case 3:
switch(x)
{
case 30:
case 32:
...
case 39:
}
break;
default :
}
In this example the switch will make 2 - 14 comparisons every time the switch is ran.
2 comparisons when x =0 : 1 in the y switch, and 1 in the x switch.
14 comparisions when x = 39 : 4 in the y switch, and 10 in the x switch.
4 comparisons when x<0 || x> 39; (default case).
now with the : int y = x/10; we have add about 7 VM instructions to the compiled code that will get executed every time the script runs. But since every comparison on the script is about 6 VM instructions, this is no big deal.
Hope that helps.
L8
Note: The discusion would be entirely different in other languages. the above applies to how nwn handles switches.
Modifié par Lightfoot8, 06 juin 2012 - 01:12 .