Anonymus methods in anonymus methods performance

S

Steeve

Hi,

I found a way to get result than I want with this anonymus method. But,
it's a little weird to use a anonymus methods in another anonymus
methods. Moreover, i have a performance issue. How can I resolve this ?

Note : NodeList is a List<Node> and ArcSuccList is a List<Arc>

Node findedNode = this.NodeList.Find(delegate(Node n)
{
if (n.Visited == true)
{ return false; }
else
{
return n.ArcSuccList.TrueForAll(delegate(Arc a)
{
return a.Visited == true;
});
}
});

Thanks,
Steeve
 
C

Carl Daniel [VC++ MVP]

Steeve said:
Hi,

I found a way to get result than I want with this anonymus method. But,
it's a little weird to use a anonymus methods in another anonymus
methods. Moreover, i have a performance issue. How can I resolve this ?

Note : NodeList is a List<Node> and ArcSuccList is a List<Arc>

Node findedNode = this.NodeList.Find(delegate(Node n)
{
if (n.Visited == true)
{ return false; }
else
{
return n.ArcSuccList.TrueForAll(delegate(Arc a)
{
return a.Visited == true;
});
}
});

Why do you think anonymous methods are the source of your performance
problem? Do you find that this code takes considerably longer that the
equivalent code written with nested for loops? There IS a cost associated
with invoking a method via a delegate, but that cost is small. There's
nothing special about anonymous methods that would change that cost unless
the anonymous method has to capture local variables from context. In that
case, each instantiation of the anonymous method will allocate an object on
the GC heap that holds the captured variables. In the code above, there
shouldn't be any captures, so the anonymous method shouldn't have any
unexpected performance overhead.

-cd
 
N

Nicholas Paldino [.NET/C# MVP]

Steeve,

You don't say what your performance issue is, or give any kind of
metrics to back this up. What do you think the issue is? The performance
of delegates is better in .NET 2.0 than it was in 1.1 and before, but it is
not as fast as direct method calls.

Here though, the problem is looping within another loop (the Find method
performs a loop action, as does TrueForAll). You should probably use
another method to find your nodes, perhaps indexing them in a way, using a
dictionary (to find based on your condition).

Hope this helps.
 
G

Guest

It is only a small issue normally which is probably unnoticable but in a loop
within a loop it might add up to something. The line:
return a.Visited == true;
could be
return a.Visited;
this would avoid calling the function to compare the two booleans and would
just return same answer.

The optimizer may even sort this out for you.

Ciaran O'Donnell
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top