Difference between declaring variables before or in loop?

前端 未结 25 2106
长发绾君心
长发绾君心 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:21

    My practice is following:

    • if type of variable is simple (int, double, ...) I prefer variant b (inside).
      Reason: reducing scope of variable.

    • if type of variable is not simple (some kind of class or struct) I prefer variant a (outside).
      Reason: reducing number of ctor-dtor calls.

提交回复
热议问题