简体   繁体   中英

Java performance when initializing variable in or outside loop?

I am wondering, from perspective of memory usage, performance and clean code, is it better to initialize variable inside or outside the loop. For example, below I show two options using variable myInt in a for loop.

Which options is better? I have a intuition on which option does what, but I want a true "Java" clarification which option is better for 1) Performance, 2) Memory and 3) Better code style.

Option 1:

int myInt = 0;
for (int i =0; i<100; i++){
   some manipulation here with myInt
}

Option 2:

for (int i =0; i<100; i++){
   int myInt = 0;
   some manipulation here with myInt
}

If you want to use the myInt within the for loop Option2 is better. You want to use it outside the loop Option1 is better. Using variables in smallest scope is better option.

Variables should always* be declared as locally as posible. If you use the integer inside the loop only, it should be declared inside the loop.

*always - unless you have a really good and proven reason not to

Well, these two options provide two different use cases:

The value of of myInt in Option2 will reset on every loop iteration, since it's scope is only within the loop.

Option1 is the way to go, if you want to something with myInt within the loop and do something with it after the loop.

I personally wouldn't care about memory or performance here, use the scope you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM