Reputation: 60682
Do I have to optimize my FOR-loops like below or the compiler will do that for me?
//this is slow, right?
for (int i = 0; i < menuItem.DropDownItems.Count; i++)
{
...
}
//this should be much faster right?
for (int i = 0, count = menuItem.DropDownItems.Count; i < count; i++)
{
...
}
PS. I bet this was already posted but I haven't found anything, sorry for a possible dup.
PPS. Sorry, I code a lot of JavaScript - where we have to think these kind of optimizations... May seem ridiculous in .net-world.
Upvotes: 17
Views: 2432
Reputation: 40669
What's the ...
part? In any question of this sort, my first response is to ask "Does it even matter, in this case?" Performance is always relative. If that exact line of code is on the stack or at the end of it more than 10% of the time, then it's worth worrying about, and that is usually very unlikely.
Upvotes: 0
Reputation: 1500855
Well, it depends on how DropDownItems.Count
is implemented - but frankly it's likely to be a simple field-backed property... which would make the first code just as fast as the second, but much more readable.
Readability first - then measure performance and micro-optimize only where necessary.
Where possible, prefer a foreach
loop to start with though... again, on grounds of readability.
Even if you do want to use a temporary variable, I would keep the for
loop itself simple, hoising the count out to separate variable. Admittedly it means a wider scope, but it's simpler:
int count = menuItem.DropDownItems.Count;
for (int i = 0; i < count; i++)
{
...
}
That much is just personal preference though.
Upvotes: 19