Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to return something [closed]

if i have a function that return something what is the best which one of the following is the best way to do it. does one follow better formatting, does one have better performance?

  private int myfunc()
{
    int value=0;
    for(int i=0;i<5;i++)
    {
        if (i==2)
            value= 2;
    }

    return value;
}

or

 private int myfunc()
{

    for(int i=0;i<5;i++)
    {
        if (i==2)
            return(2);
    }

   return (0);
}
like image 610
user979490 Avatar asked Jan 19 '23 14:01

user979490


1 Answers

I prefer the second approach.

Anyway you won't notice any performance difference in either ways if you correct the implementation of the first approach by 'break'ing the loop once you find the item you want.

It's a good programming practice not to declare variables unnecessarily. What you have done in the second approach is good in that way. And the second approach does not execute all the cycles in the for loop. So another good point.

If you do this for the first approach. Both will perform almost the same except declaring unwanted variable in the first approach. First approach gives some work for the garbage collector that doesn't happen in the second approach.

for(int i=0;i<5;i++)
    {
        if (i==2)
        {
            value= 2;
            break;
         }
    }
like image 59
CharithJ Avatar answered Jan 29 '23 06:01

CharithJ