HomeUser Control Panel (unavailable in archive)ForumsTutorialsArt GalleryResourcesMaps

Efficiency of AND operator

03-15-2006, 03:51 AM#1
Azazel_
Question
Which is more efficient?

Choice A

Collapse JASS:
    if (GetPlayerState(p,PLAYER_STATE_RESOURCE_GOLD)==0) then
        if (GetPlayerState(p,PLAYER_STATE_RESOURCE_LUMBER)==0) then
            set udg_Reloading[GetConvertedPlayerId(p)]=3
        endif
    endif

Choice B

Collapse JASS:
    if (GetPlayerState(p,PLAYER_STATE_RESOURCE_GOLD)==0 and GetPlayerState(p,PLAYER_STATE_RESOURCE_LUMBER)==0) then
        set udg_Reloading[GetConvertedPlayerId(p)]=3
    endif

=================

Answer

Test Method
- udg_a, udg_b initialized to zero

Collapse JASS:
function rtrue takes nothing returns boolean
   set udg_b = 1
   return true
endfunction

function rfalse takes nothing returns boolean
   set udg_a = 1
   return false
endfunction

function Trig_test_Actions takes nothing returns nothing
    if(rfalse() and rtrue()) then
        call DoNothing()
    endif
    call BJDebugMsg("a: "+I2S(udg_a)+"  b: "+I2S(udg_b))
endfunction
During this test, rtrue's value did not change at all, while rfalse's increased n times.

Credits to Pipedream for conducting the research and answering this question for me. Choice B is the more efficient alternative, because AND stops running if the first value is false. However, in this specific example, the main reason is that B is shorter in terms of code length. An application of this knowledge is to order your conditions with account to two factors :

Rarity
If ( ReallyRareThing AND NotTooRare AND QuiteFrequent ) then

Complexity of Code
If ( VeryLittleProcess AND ModerateProcess AND ProcessIntensive ) then
03-15-2006, 02:16 PM#2
Chuckle_Brother
Just a thought but wouldn't you want to place the process intensive code first since it is the most likely? That way if it is true at that given time you save on the processing for the other conditions, but I dunno...maybe I'm off my rocker.
03-15-2006, 02:35 PM#3
Azazel_
We will use the ceteris paribus assumption for process considerations, ie. the likelihood of each type occuring are similiar. Hence, it is better to run the lightest process first.
03-15-2006, 02:39 PM#4
blu_da_noob
I believe this is called something like 'short circuit' boolean checking. I heard something about it on the BNet forums.

As for the order in which you should place boolean statements, I think a combination of complexity and rarity would be the best for maximum efficiency.
03-16-2006, 12:52 AM#5
Azazel_
Yes, accounting for both factors is the best for efficiency.