简体   繁体   中英

for-loop optimization - needed or not?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM