Is it better to declare a variable inside or outside a loop?

后端 未结 6 2003
眼角桃花
眼角桃花 2020-12-01 07:55

Is better do:

variable1Type foo; 
variable2Type baa; 

foreach(var val in list) 
{
    foo = new Foo( ... ); 
    foo.x = FormatValue(val); 

    baa = new B         


        
6条回答
  •  悲哀的现实
    2020-12-01 08:13

    Both are completely valid, not sure there's a 'right way' to do this.

    Your first case is more memory-efficient (at least in the short term). Declaring your variables inside the loop will force more reallocation of memory; however, with .NETs garbage collector, as those variables go out of scope they will be cleaned up periodically, but not necessarily immediately. The difference in speed is arguably negligible.

    The second case is indeed a bit safer, as limiting the scope of your variables as much as possible is usually good practice.

提交回复
热议问题