Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I redefine or reassign a variable in a loop? [duplicate]

Supposing I need to iterate over something and set a variable in every cycle, like this:

for (int i=0; i < list.size(); i++) {
    final Object cur = list.get(i);
}

this redefines the variable everytime, so I'm concerned that that might pollute the memory.

The alternate option is to define the variable once and then reassign it every iteration, like this:

Object cur
for (int i=0; i < list.size(); i++) {
    cur = list.get(i);
}

would this be better in terms of memory? Would it make any difference? What if cur is a primitive type instead of an Object?

Don't tell me to use foreach, I need the counter, this is just a simplified example

like image 607
xeruf Avatar asked Nov 28 '25 20:11

xeruf


1 Answers

From a performance point of view, I would say if you need to improve this (you measured that a hot spot was here), you can choose the solution that offers best performances.

That said, I would recommend putting it inside the loop so that you cannot use it by error outside.

BTW, you'll ease debugging and readability by not having a variable that is there without knowing if it should or not be used outside the loop.

like image 57
OznOg Avatar answered Dec 01 '25 10:12

OznOg



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!