Declare an object inside or outside a loop?

前端 未结 16 807
广开言路
广开言路 2020-12-07 17:15

Is there any performance penalty for the following code snippet?

for (int i=0; i         


        
16条回答
  •  旧巷少年郎
    2020-12-07 17:55

    In both cases the type info for the object o is determined at compile time.In the second instance, o is seen as being global to the for loop and in the first instance, the clever Java compiler knows that o will have to be available for as long as the loop lasts and hence will optimise the code in such a way that there wont be any respecification of o's type in each iteration. Hence, in both cases, specification of o's type will be done once which means the only performance difference would be in the scope of o. Obviously, a narrower scope always enhances performance, therefore to answer your question: no, there is no performance penalty for the first code snip; actually, this code snip is more optimised than the second.

    In the second snip, o is being given unnecessary scope which, besides being a performance issue, can be also a security issue.

提交回复
热议问题