Which is optimal?

前端 未结 8 516
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 21:23

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

eg

8条回答
  •  [愿得一人]
    2020-12-11 21:55

    Well, if you are worrying about optimizing that code - I'm not sure about how Java evaluates for loops, but having the list.size() being called inside the loop declaration maybe less efficient than outide the loop (and setting it to a varable listLength perhaps). I'm pretty sure that method is quicker in JavaScript. The reason it might be more efficient is that having the size function call inside the for loop means it would have to go call the function each time it runs the test to see if the loop is finished, instead of testing against a static value.

提交回复
热议问题