1

Possible Duplicate:
Difference between declaring variables before or in loop?

Is there any (or any notable) performance difference when I write for example something like this (consider loading tens or hundreds of thousands rows from DB into the collection of Foo objects):

...
Foo myFoo;

while(reader.Read())
{
    myFoo = new Foo();
    myFoo.SomeProperty = reader.GetValue(0);
    ...
    fooCollection.Add(myFoo);
}

or this

...

while(reader.Read())
{
    Foo myFoo = new Foo();
    myFoo.SomeProperty = reader.GetValue(0);
    ...
    fooCollection.Add(myFoo);
}
Community
  • 1
  • 1
yojimbo87
  • 65,684
  • 25
  • 123
  • 131

2 Answers2

4

You're creating a new instance of Foo in each iteration of the loop in both snippets so I wouldn't expect to see a difference.

You should profile your code though, using a tool like eqatec profiler:

http://www.eqatec.com/tools/profiler

Charlie
  • 10,227
  • 10
  • 51
  • 92
2

Actually the compiler will generate the same IL in each instance.

See similar questions here and here.

Community
  • 1
  • 1
Winston Smith
  • 21,585
  • 10
  • 60
  • 75