Vahan
Vahan

Reputation: 3288

Is it better to save getter value in variable instead of calling get many times?

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());
}

Upvotes: 1

Views: 1563

Answers (3)

GedankenNebel
GedankenNebel

Reputation: 2597

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.

Upvotes: 1

John Snow
John Snow

Reputation: 5344

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);
}

Upvotes: 0

Rahul
Rahul

Reputation: 45090

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.
}

Upvotes: 2

Related Questions