Difference between declaring variables before or in loop?

前端 未结 25 2461
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:14

    A co-worker prefers the first form, telling it is an optimization, preferring to re-use a declaration.

    I prefer the second one (and try to persuade my co-worker! ;-)), having read that:

    • It reduces scope of variables to where they are needed, which is a good thing.
    • Java optimizes enough to make no significant difference in performance. IIRC, perhaps the second form is even faster.

    Anyway, it falls in the category of premature optimization that rely in quality of compiler and/or JVM.

提交回复
热议问题