Is it faster or faster to finish the code?

If I have a method containing many if else statements, for example:

public void myMethod()
{
    if(..)
    else if(..)
    else if(...)
    else if(...)
    else if(...)

    //and so on            
}

Would it be faster to place the return inside these statements, so that the rest of the code will not be checked after one statement is found as true, or would it be faster to let the compiler fall into the final bracket?

I think it comes down to the question: is the return statement efficient or not?

EDIT: Question: Say you have a game loop that is constantly working, with code that contains many methods and "else ifs". If I need to update 2,000 different objects 60 times per second, then 120,000 "else ifs" are checked (at least) per second. Thus, answering a question can potentially make a difference over time.

+5
3

.
- . (, , , )

, .

+18

SLaks, , . , , , , , -else .

if(x) X();
else if(y) Y();
else if(z) Z();
return;

,

if(x)
{
  X();
}
else
{
  if (y)
  {
    Y();
  }
  else
  {
    if (z)
    {
      Z();
    }
  }
}
return;

, , x, y ; return X().

, , "else if" # C, ++, Java JavaScript. ""; else if, . "else if",

if (x) X();
else while(y) Y();

- else while. , else; if , , . (*)

UPDATE:

, else, "", , , , . , , if else . ( ). ?

, . if-else :

if (condition) 
    Consequence() 
else 
    Alternative();
Continuation();

goto:

if (!condition) 
    goto ALTERNATIVE;
Consequence();
goto CONTINUATION;
ALTERNATIVE:  Alternative();
CONTINUATION: Continuation();

,

if (x) X(); 
else if (y) Y();
else if (z) Z();
return;

if (x)
    X(); 
else 
{
    if (y)
        Y();
    else
    {
        if (z)
            Z();
    }
}

if (!x) goto XALTERNATIVE;
X(); 
goto CONTINUATION;
XALTERNATIVE: if (!y) goto YALTERNATIVE;
Y();
goto CONTINUATION;
YALTERNATIVE: if (!z) goto CONTINUATION;
Z();
CONTINUATION: return;

?


(*) ; # .

+12

It is effective when used as a protection for conditions, but in your case it does not matter, because as soon as one of these statements is executed, the others are not checked, but if you do something like this:

if(...){return;}
if(...){return;}
if(...){return;}
if(...){return;}
if(...){return;}

Then it matters.

0
source

All Articles