Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this "move declaration closer to usage" really preferable? [duplicate]

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

Resharper wants me to change this:

int Platypus;
string duckBill1;
string duckBill2;
string duckBill3;
. . .
using (OracleDataReader odr = ocmd.ExecuteReader()) {
    while (odr.Read()) {
        Platypus = odr.GetInt32("Platypus");
        duckBill1 = odr.GetString("duckBill1");
        duckBill2 = odr.GetString("duckBill2");
        duckBill3 = odr.GetString("duckBill3");
        switch (Platypus) {
        . . .

...to this:

using (OracleDataReader odr = ocmd.ExecuteReader()) {
    while (odr.Read()) {
        int Platypus = odr.GetInt32("Platypus");
        string duckBill1 = odr.GetString("duckBill1");
        string duckBill2 = odr.GetString("duckBill2");
        string duckBill3 = odr.GetString("duckBill3");
        switch (Platypus) {
        . . .

...but in this way (it seems, at least, that) the vars are being declared N times, once for each time through the while loop. Is the Resharperized way really better than the original?

like image 988
B. Clay Shannon-B. Crow Raven Avatar asked Aug 16 '12 16:08

B. Clay Shannon-B. Crow Raven


1 Answers

Yes, it is better because you're limiting the scope of the declared variables. There will be no performance impact for declaring them inside the loop. The reason Resharper is suggesting this change is that you're not using them outside of the loop.

like image 101
rsbarro Avatar answered Oct 05 '22 22:10

rsbarro