Home Should I redefine or reassign a variable in a loop?
Reply: 0

Should I redefine or reassign a variable in a loop?

user1141
1#
user1141 Published in May 24, 2018, 4:00 pm

This question already has an answer here:

  • Difference between declaring variables before or in loop? 24 answers

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.405861 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO