1

I have Item item; which has getName() getter. I need to acces item.getName() in some loop. Is it better to call item.getName() in loop each time, or save it in additional variable and use that variable and is there difference?

For example: Item item;

String itemName=item.getName();

for(int i=0;  i< itemArray.size();i++){

    itemArray.get(i).setName(itemName);
}

or

for(int i=0; i< itemArray.size();i++){

    itemArray.get(i).setName(item.getName());
}
4
  • I don't have any probles with value changes, that's not my question. Commented Apr 23, 2013 at 11:27
  • This new edited Code would set all items in your array to the same name. If this is what you want it's better to use a variable and call getName() once, instead of calling getName() each iteration. Altho finetuning like this is not anyting that would be noticable from the user point of view Commented Apr 23, 2013 at 11:37
  • That's not the exactly what I need, but some example like that. I know that it isn't noticeable. But which style is better because having additioonal variable has also it's disatvantages. Commented Apr 23, 2013 at 11:43
  • Then I would say the second example, less code and no real performance difference Commented Apr 23, 2013 at 11:48

3 Answers 3

2

If you're gonna re-assign item over and over again in your loop, then you need to use item.getName(), else you can just store the value in a local variable, and use that in the loop. And if you're not gonna change its value, then you can make it final too.

E.g:

final String name = item.getName();
while(comdition){ // some loop
    // something involving name. But not modifying it.
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you use item.getName() you will get always the current fresh value. Saving it into an additional variable while iterating over it may will not see changes. If this is your intent its ok and declare it as final as it will be thread-safe. Otherwise I don´t think this will be a big performance issue. Keep using the getter.

Comments

0

Which one would you prefeer?

String itemName;

for(int i=0;i<itemArray.size();i++){
   itemName=itemArray.get(i).getName();
   System.out.println(itemName);
}

or

for(int i=0;i<itemArray.size();i++){
   System.out.println(itemArray.get(i).getName);
}

1 Comment

well, I see no reason why the first example would be better. The second example is better for both readability and performance (altho it will not be any noticable performance difference)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.