开发者

Variable reuse - which is better practice?

开发者 https://www.devze.com 2023-03-05 21:26 出处:网络
Is reusing variables a good or bad thing or does it not make a difference? Should I be doing this: void someMetho开发者_如何转开发d (byte[] arrayOfBytes)

Is reusing variables a good or bad thing or does it not make a difference?

Should I be doing this:

void someMetho开发者_如何转开发d (byte[] arrayOfBytes)
{
   byte[] newArrayOfBytes = someOtherMethod(arrayOfBytes);

   // ...
}

or this:

void someMethod (byte[] arrayOfBytes)
{
   arrayOfBytes = someOtherMethod(arrayOfBytes);

   // ...
}

or does it make no difference at all?


I would not lose any sleep on this. The memory cost of the extra reference variable(s) is negligible. I'd prefer the newArrayOfBytes method just for safety - it's not considered great practice to reassign a parameter coming into a method and it may lead to bugs later on, when a developer does not realise the parameter has changed to refer to another Object (you'll see some developers mark the method params as final, to prevent this)


If you can do it without getting confused or confusing others then it is a good thing, because your code will require less memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号