I need to optimize this code so it can execute faster, even if that means using more memory:
for (int t = 0; t < Clientes[0].ChildNodes.Count; t++)
{
for (int i = 0; i < Clientes[0].ChildNodes.Item(t).ChildNodes.Count; i++)
{
if (Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.Contains("Service"))
{
int a = 0;
int.TryParse(Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.ToUpper().Replace("SERVICE", ""), out a);
if (a.Equals(Type))
{
Queues[t].Send(QueueMessage);
}
}
}
}
I have decided to avoid accessing Clientes[0]
and its ChildNodes.Item(t)
over and over in each loop by keeping them in new variables like this:
XmlNodeList clientZeroChildNodes ;
int clientZeroChildCount ;
XmlNodeList clientZeroItemTchildNodes ;
int clientZeroItemTchildCount;
string clientZeroItemTchildIname;
clientZeroChildNodes = Clientes[0].ChildNodes;
clientZeroChildCount = clientZeroChildNodes.Count;
for (int t = 0 ; t < clientZeroChildCount ; t++)
{
clientZeroItemTchildNodes = clientZeroChildNodes.Item(t).ChildNodes;
clientZeroItemTchildCount = clientZeroItemTchildNodes.Count;
for (int i = 0; i < clientZeroItemTchildCount; i++)
{
clientZeroItemTchildIname = clientZeroItemTchildNodes.Item(i).Name;
if (clientZeroItemTchildIname.Contains("Service"))
{
int a = 0;
int.TryParse(clientZeroItemTchildIname.ToUpper().Replace("SERVICE", ""), out a);
if (a.Equals(Type))
{
try
{
Queues[t].Send(QueueMessage);
}
catch (MessageQueueException mqe)
{
//log error about mqe
}
}
}
}
}
As you can see, the second for
loop only takes certain items of the ChildNodes
based on its name. I have tried to use LINQ so that the second for
only iterates the list of ChildNodes
that match both of the if conditions that are inside the loop but have not been able to do it.
Can you show me how would you improve the speed of the original code focusing on an efficient way to improve the loops and nested if
s? I am not trying to determine which line of code is taking longer and the performance of the Queues
is not relevant for me.
Queues[t].Send(QueueMessage);
? \$\endgroup\$