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

Should I redefine or reassign a variable in a loop?

Xerus Published in 2017-11-14 20:18:26Z

This question already has an answer here:

  • Difference between declaring variables before or in loop? 23 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

VHS Reply to 2017-11-14 20:24:53Z

I would recommend you use your alternate approach - declaration of a variable - primitive or object outside the loop. However, I notice in your first approach that you are declaring the object with final keyword. This should give a hint to the compiler to optimize the code in a way that the memory utilization at the run time is as less as possible. But you shouldn't rely on that. Just use your alternate approach.

OznOg Reply to 2017-11-14 20:25:30Z

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.

Tharun Reply to 2017-11-14 20:26:48Z

It has no effect on performance. Both are good. They turn out to be compiled to similar bytecode as pointed by this blogpost :(http://livingtao.blogspot.in/2007/05/myth-defining-loop-variables-inside.html)

Eugene Reply to 2017-11-14 20:30:57Z

Seriously use whatever you want, it will have no difference. The only difference is the scope of that variable - for example it would be much simpler to reason about the variable GC when it is inside the loop - because it basically can not "escape" the loop.

Simmant Reply to 2017-11-14 20:48:15Z

Performance of program is depend on how much time your code is taking to produce the output, and Statement/Loops/Conditions which take more time to execute it is natural that peace of code will consume more memory then other code which take less time to generate the output.

As per your code concern, 1st loop statement where you assigning final Object on every iteration is takes more time as compare to second loop statement where it assign to same object every time.

What I tried in my local linux(Ubuntu) box, 1st statement take 18 milliseconds while 2nd statement takes only 15 seconds, so I guess 2nd statement will be more appropriate.

Code which I tried locally:

import java.util.ArrayList;
import java.util.List;

public class Solution8 {

    public static void main(String[] args) {
        List<String> lis = new ArrayList<String>();

        for (int i = 0; i <= Math.pow(10, 5); i++) {
            lis.add(i + "");
        long startTime = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            final Object cur1 = lis.get(i);
        long endTime = System.currentTimeMillis();

        System.out.println("1st : "+(endTime-startTime)); // 18 milliseconds 
        Object cur;
        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            cur = lis.get(i);
        long endTime2 = System.currentTimeMillis();

        System.out.println("2nd : "+(endTime2-startTime2)); // 15 milliseconds


Hope this will help.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO