Raised This Month: $ Target: $400
 0% 

[Optimize] Loop


  
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
e12harry
Member
Join Date: Apr 2010
Old 09-26-2011 , 08:18   Re: [Optimize] Loop
Reply With Quote #6

Acording to: http://wiki.alliedmods.net/Optimizin...X_Scripting%29



Quote:
new team = get_user_team(player)
if (team == TEAM_T)
{
//...code
} else if (team == TEAM_CT) {
//...code
} else if (team == TEAM_SPECTATOR) {
//...code
}

Now, the compiler will only generate this:

CALL get_user_team
COMPARE+BRANCH
COMPARE+BRANCH
COMPARE+BRANCH

If get_user_team were an expensive operation (it's relatively cheap), we would have recalculated the entire result each branch of the if case.
Switch instead of If

If you can, you should use switch cases instead of if. This is because for an if statement, the compiler must branch to each consecutive if case. Using the example from above, observe the switch version:

new team = get_user_team(player)
switch (team)
{
case TEAM_T:
//code...
case TEAM_CT:
//code...
case TEAM_SPECTATOR:
//code...
}

This will generate what's called a "case table". Rather than worm through displaced if tests, the compiler generates a table of possible values, which the virtual machine knows to browse through:

CALL get_user_team
COMPARE
COMPARE
COMPARE
PHP Code:
 if ( CS_TEAM_T <= cs_get_user_teamiPlayer ) <= CS_TEAM_CT 
will take more operations than switch.
You can use:
PHP Code:
switch(cs_get_user_team(player))
        {
            case 
CS_TEAM_SPECTATOR CS_TEAM_UNASSIGNED:
            {
                
/*Remove Players From Loop*/
                
continue;
            }

        }
        
MainMenu(player); 
or
PHP Code:
switch(cs_get_user_team(player))
        {
            case 
CS_TEAM_T CS_TEAM_CT:
            {
               
MainMenu(player);
            }
        } 

As you can see in this case it is not worth arguing, but still I think switch is more efficient.

Last edited by e12harry; 09-26-2011 at 08:38.
e12harry is offline
 



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 19:35.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode