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);
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With