SWITCH vs IF-ELSE

Moderator: Event DM

Post Reply
User avatar
keikobad
Sage
Posts: 1983
Joined: Sat Apr 26, 2003 7:05 am

SWITCH vs IF-ELSE

Post by keikobad » Wed Mar 31, 2004 8:19 am

Anyone know if the NWscript compiler optimizes large switch statements over the equivalent series of if-else statements?

In C, I'd expect that a good compiler would try to set up a binary search or some such through the list of cases, instead of evaluating them all until the right one is found. If the case labels consisted of regularly incremented values, performance might be even better.

If there's any evidence that NWN does the same, could it help to deal with the scripts that go through the large list of Avlis items when an unique item is activated? Or is that already done?
User avatar
_LuCkY_
Scholar of Fools
Posts: 476
Joined: Tue Apr 29, 2003 10:25 am
Location: Netherlands

Post by _LuCkY_ » Wed Mar 31, 2004 8:43 am

I suppose you could test it by making two big loops. One with a if-then-else statement and one with a switch statement. Run it a couple of times and measure the time it takes to execute (I don't think this can be done in the script, so you'll have to make a really big loop and use a stopwatch or so :)). I doubt that it will change much in NWscript though.

The big advantage of a switch statement is that the statement that is to be evaluated is evaluated only once (and probably stored in a register).
User avatar
Dirk Cutlass
Elder Sage
Posts: 4691
Joined: Mon Jan 27, 2003 9:42 am
Location: GMT

Post by Dirk Cutlass » Wed Mar 31, 2004 9:08 am

Of course you can optimize both 'swicth' and 'if/else if' constructs yoursefl (manually) by putting the most common possibilities nearer the top, and hopefully these will be tested first.

I've never heard of the 'binary search' optimization that you describe - it sounds a bit too specialised to me! Only really suited for switches where you have a large number of integer values to check - and even then how does the compiler know the 'frequency' of each number, e.g suppose you had a switch of 100 values, the binary search would start at 50 and work outwards. But if '1' was the most common, and all other values are much less frequent then this binary search would be wasting its time most of the time.

Anyway, I doubt that the NWN script compiler is that intelligent - but I could be wrong.
Halvar Yanocen
Apprentice Scholar
Posts: 854
Joined: Mon Sep 29, 2003 10:11 pm
Location: GMT+2

Post by Halvar Yanocen » Wed Mar 31, 2004 11:35 am

If you want a fast switch statement do the following (in pseudocode):
shiftleft flag, magicnumber, adress
jump adress + programcounter
This means that you will jump directly to the right case statement. Ofcours you will have to pad all case blocks to be of the same size (the magic number).

But this doesn't have anything to do with scripting in NWN :).
The forest is vast and the council of nine is far away.
Post Reply