Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Performance setting value for each list item
    text
    copied!<p>I am trying to find the fasted way to set a specific property of every item in a generic list.</p> <p>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.</p> <p>My first attempt looked like this:</p> <pre><code>listItems.ForEach(delegate(Item i) { i.IsHit = false; }); foreach (int hitIndex in hits) { listItems[hitIndex - 1].IsHit = true; } </code></pre> <p>Note: hits is 1-based, the items list is 0-based.</p> <p>Then i tried to improve the speed and came up with this:</p> <pre><code>for (int i = 0; i &lt; listItems.Count; i++) { bool hit = false; for (int j = 0; j &lt; 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; } } </code></pre> <p>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 ;-)</p> <p>Unfortuanetly I don't really see any way to improve the code further. But I probably missed something.</p> <p><br><br> Thanks</p> <p>PS: Code in C# / .NET 2.0 would be preferred.</p> <hr> <p>I ended up switching to Eamon Nerbonne solution. But then I noticed something weird in my benchmarks.</p> <p>The delegate:</p> <pre><code>listItems.ForEach(delegate(Item i) { i.IsHit = false; }); </code></pre> <p>is faster than:</p> <pre><code>foreach (Item i in listItems) { i.IsHit = false; } </code></pre> <p>How is that possible?</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload