Which is optimal?

前端 未结 8 535
被撕碎了的回忆
被撕碎了的回忆 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:45

    Besides the useful suggestions given by others, please do keep in mind one thing:

    never optimize early. If you really think your code is slow and might need improvement, then use a profiler for your code to spot where the bottlenecks are, and only then do refactor them. Learn where the mistake was. Do not repeat mistake next time.

    In your case I would say that, depending on the java VM version, your performance (guess what) might vary. Out of experience I'd not declare a variable within a loop; an int will certainly be optimized out by the compiler and re-use the same memory address, and the extra computational cost might be negligible.

    But.

    If you were declaring an object inside a loop, then things will be different. What if your object, when created, does an I/O write? A network DNS lookup? You might not know/care. So, best practice is declare it ouside.

    Also, do not mix up performance with best practice. They might lead you into dangerous territory.

提交回复
热议问题