2

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
}
2
  • The general advice (from Effective Java for example) is to keep the scope of variables as small as possible. Commented Jan 10, 2018 at 10:19
  • In addition to the answers already given: You need exactly the same stack space. Performance impact for primitive values (like in the example) is negligible. This may be different if you construct a complex object. Commented Jan 10, 2018 at 10:22

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.