| Author |
Any difference between these two ways of returning ?
|
David Jason
Greenhorn
Joined: Aug 21, 2012
Posts: 27
|
|
returnAboolean();
//do something else
or
boolean boo = returnAboolean();
//do something else
Does the 2nd one consume a little more memory ?
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3041
|
|
Are you asking if more memory is consumed by holding the value returned from a method (boolean bool = getABoolean();) versus not holding the value returned from the method (getABoolean();)?
If the answer is yes, the amount of memory being 'saved' would be so inconsequential as to not be worth thinking about. If you need the returned value, store it in a variable. If you don't care about the returned value and just call the method for another affect, then don't store the returned value in a variable. But the memory consideration shouldn't come into the picture.
|
Steve
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
Your first example returns something and the second assigns something. They are completely different from each other. Like chalk and cheese.
I presume you meant to ask whether creating a local variable and returning it requires more memory. Yes. A lot. One bit. Maybe even a whole byte. Since local vraiables live on the stack they are deleted immediatly, so it won’t make much difference. You meant to ask which of the following is more efficient:-No problem; neither of those methods will compile, because they contain unreachable code.
I prefer versions without unnecessary variables, the next rather than the fourth example:-There are however instances where a local variable is very useful, like in this equals method (there are other ways to implement it):-Note that use of the && operator prevents null exceptions and class cast exceptions. If ob is null, then equals is false and none of the other tests is ever applied.
|
 |
David Jason
Greenhorn
Joined: Aug 21, 2012
Posts: 27
|
|
Steve Luke wrote:Are you asking if more memory is consumed by holding the value returned from a method (boolean bool = getABoolean();) versus not holding the value returned from the method (getABoolean();)?
If the answer is yes, the amount of memory being 'saved' would be so inconsequential as to not be worth thinking about. If you need the returned value, store it in a variable. If you don't care about the returned value and just call the method for another affect, then don't store the returned value in a variable. But the memory consideration shouldn't come into the picture.
I understand that the amount of memory consumed will be too small/insignificant. I was interested in knowing if there would be a difference, no matter how small.
|
 |
 |
|
|
subject: Any difference between these two ways of returning ?
|
|
|