Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Where should I initialise variables for memory efficiency?

Is it okay for memory to initialise a variable inside a method that will be called rather frequently? Basically, is this example method:

int amount;
private boolean method() {
    amount = Random.nextInt(0, 100);
    return amount == 50;
}

More/less/the same in terms of memory efficiency to this method:

private boolean method() {
    int amount = Random.nextInt(0, 100);
    return amount == 50;
}

And yeah, I know these aren't the best examples, and that there is some redundancy to them. Sorry about that.

Anyway, thanks in advance.

like image 810
Hat Avatar asked Dec 05 '25 00:12

Hat


1 Answers

The difference in efficiency, if any, is highly likely to be completely irrelevant. If amount does not need to be visible outside the method, prefer the second version as it does not have unnecessary side effects and is thread-safe.

To expand on the last point, if multiple threads were to call method() on the same object, the first version is open to a race condition.

like image 149
NPE Avatar answered Dec 06 '25 15:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!