is there a foreach performance issue when using complex expressions?

  • Thread starter Thread starter Benjamin Joldersma
  • Start date Start date
B

Benjamin Joldersma

Hi all,

If I have a expensive public property that exposes a collection, say
via a call to a database:

public ArrayList Complex
{
get
{
//expensive call to db
return DbResult;
}
}

and use this in a foreach:

foreach( object o in Complex )
{
...
}

Will the clr call Complex only once, and save a reference to the
direct variable actually exposed, or will it execute the code in the
get routine each iteration?

Thanks in advance,

Ben Joldersma
Sr. Software Engineer,
Citadel Media, Inc.
 
Will the clr call Complex only once, and save a reference to the
direct variable actually exposed, or will it execute the code in the
get routine each iteration?

It calls it once, and gets an iterator. So no, you don't need to worry
about the time it takes to evaluate that.
 
Hi Benjamin,

It call it once.

This is VERY easy to check ( I just did it ), just put a breakpoint inside
the get method , you will see it only enters once.

Cheers,
 
Back
Top