Home Java performance when initializing variable in or outside loop?
Reply: 3

Java performance when initializing variable in or outside loop?

Dark Templar
Dark Templar Published in 2018-01-10 09:53:23Z

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
maio290 Reply to 2018-01-10 09:58:34Z

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.

esparklight Reply to 2018-01-10 10:06:14Z

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.

Dariusz Reply to 2018-01-10 10:19:14Z

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

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO