[英]Is it better to save getter value in variable instead of calling get many times?
I have Item item; 我有Item项目; which has getName() getter.
它有getName()getter。 I need to acces item.getName() in some loop.
我需要在某个循环中访问item.getName()。 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?
最好每次在循环中调用item.getName(),还是将其保存在附加变量中并使用该变量并且有区别吗?
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());
}
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. 如果你要在循环中一遍又一遍地重新分配
item
,那么你需要使用item.getName()
,否则你只需将值存储在局部变量中,并在循环中使用它。 And if you're not gonna change its value, then you can make it final
too. 如果你不会改变它的价值,那么你也可以做到
final
。
Eg: 例如:
final String name = item.getName();
while(comdition){ // some loop
// something involving name. But not modifying it.
}
When you use item.getName() you will get always the current fresh value. 当您使用item.getName()时,您将始终获得当前的新值。 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.
如果这是你的意图,那就确定并将其声明为final,因为它是线程安全的。 Otherwise I don´t think this will be a big performance issue.
否则我不认为这将是一个很大的性能问题。 Keep using the getter.
继续使用吸气剂。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.