Java : declaring objects in a loop [duplicate]

流过昼夜 提交于 2019-12-24 07:25:15

问题


Is there any difference between

for (...) {
  String temp = "temp";
}

and

String temp;
for (...) {
  temp = "temp";
}

I mean, does Java waste many resources creating/deleting objects in loop?

Thank you.


回答1:


The difference is in scope of variable.

  • Defined inside loop means visible only inside the loop.

  • Defined outside the loop means visible inside and outside the loop.

does Java waste many resources creating/deleting objects in loop?

if defined inside the loop then it will be re-intialized with every iteration, which means an extra executable statement. If you want to re-intialize it with each iteration then good otherwise move it out to save wasted cpu for that statement.




回答2:


The only difference is the issue of scope. With the variable being declared outside the for-block, the variable (object reference) can be accessed outside the for-loop block.

If the object reference variable is declared inside the for-loop, then it can only be accessed within the for-loop block.




回答3:


First the two scope variables.

  1. define inside the loop will be visible only to loop.
  2. define outside the loop will be visible to inside and outside the loop

Java waste many resources creating/deleting

Java creates as many objects of String as many times you are iterating your loop but the reference will be same. So its a bit resource and memory consuming. Use StringBuilder or StringBuffer.




回答4:


for (...) 

{

String temp = "temp";

}

In this case your temp would be available only for For loop

String temp;

for (...)

 {

  temp = "temp";

}

And here If you are writing this code inside a method then it would be available throughout the method.

Note:- Local variables are created in Stack and are removed after execution of that method.



来源:https://stackoverflow.com/questions/21020432/java-declaring-objects-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!