Declaring variables inside or outside of a loop

前端 未结 20 2641
后悔当初
后悔当初 2020-11-22 01:59

Why does the following work fine?

String str;
while (condition) {
    str = calculateStr();
    .....
}

But this one is said to be dangerou

20条回答
  •  生来不讨喜
    2020-11-22 02:54

    Declaring objects in the smallest scope improve readability.

    Performance doesn't matter for today's compilers.(in this scenario)
    From a maintenance perspective, 2nd option is better.
    Declare and initialize variables in the same place, in the narrowest scope possible.

    As Donald Ervin Knuth told:

    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

    i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.

提交回复
热议问题