Difference between declaring variables before or in loop?

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

    I've always thought that if you declare your variables inside of your loop then you're wasting memory. If you have something like this:

    for(;;) {
      Object o = new Object();
    }
    

    Then not only does the object need to be created for each iteration, but there needs to be a new reference allocated for each object. It seems that if the garbage collector is slow then you'll have a bunch of dangling references that need to be cleaned up.

    However, if you have this:

    Object o;
    for(;;) {
      o = new Object();
    }
    

    Then you're only creating a single reference and assigning a new object to it each time. Sure, it might take a bit longer for it to go out of scope, but then there's only one dangling reference to deal with.

提交回复
热议问题