Declaring variables inside or outside of a loop

前端 未结 20 2062
后悔当初
后悔当初 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:52

    I think the best resource to answer your question would be the following post:

    Difference between declaring variables before or in loop?

    According to my understanding this thing would be language dependent. IIRC Java optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation each time in the loop.In Java particularly I think the second would run faster when done profiling.

提交回复
热议问题