Difference between declaring variables before or in loop?

前端 未结 25 2074
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-11-22 03:09

    It's an interesting question. From my experience there is an ultimate question to consider when you debate this matter for a code:

    Is there any reason why the variable would need to be global?

    It makes sense to only declare the variable once, globally, as opposed to many times locally, because it is better for organizing the code and requires less lines of code. However, if it only needs to be declared locally within one method, I would initialize it in that method so it is clear that the variable is exclusively relevant to that method. Be careful not to call this variable outside the method in which it is initialized if you choose the latter option--your code won't know what you're talking about and will report an error.

    Also, as a side note, don't duplicate local variable names between different methods even if their purposes are near-identical; it just gets confusing.

提交回复
热议问题