Hello,
I am trying to find the fasted way to set a specific property of every item in a generic list.
Basicly the requirement is to iterate over a list of items and resetting the IsHit property to FALSE. Only the items in a second "hit"-list should be set to TRUE afterwards.
My first attempt looked like this:
listItems.ForEach(delegate(Item i) { i.IsHit = false; });
foreach (int hitIndex in hits)
{
listItems[hitIndex - 1].IsHit = true;
}
Note: hits is 1-based, the items list is 0-based.
Then i tried to improve the speed and came up with this:
for (int i = 0; i < listItems.Count; i++)
{
bool hit = false;
for (int j = 0; j < hits.Count; j++)
{
if (i == hits[j] - 1)
{
hit = true;
hits.RemoveAt(j);
break;
}
}
if (hit)
{
this.listItems[i].IsHit = true;
}
else
{
this.listItems[i].IsHit = false;
}
}
I know this is a micro optimization but it is really time sensitive code, so it would make sense to improve this code beyond readibility... and just for fun of course ;-)
Unfortuanetly I don't really see any way to improve the code further. But I probably missed something.
Thanks
PS: Code in C# / .NET 2.0 would be preferred.
I ended up switching to Eamon Nerbonne solution. But then I noticed something weird in my benchmarks.
The delegate:
listItems.ForEach(delegate(Item i) { i.IsHit = false; });
is faster than:
foreach (Item i in listItems)
{
i.IsHit = false;
}
How is that possible?
I tried to look at IL but thats just way over my head... I only see that the delegates results in fewer lines, whatever that means.