for循环优化 - 需要与否? [英] for-loop optimization - needed or not?

查看:138
本文介绍了for循环优化 - 需要与否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定要优化我的for循环像下面或编译器会为我做的?

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。我敢打赌,这是已经发布,但我没有发现任何东西,对不起,可能DUP。

PS. I bet this was already posted but I haven't found anything, sorry for a possible dup.

PPS。对不起,我编写一个大量的JavaScript - 在这里我们不得不考虑这类优化......看起来似乎在.NET世界的荒谬

PPS. Sorry, I code a lot of JavaScript - where we have to think these kind of optimizations... May seem ridiculous in .net-world.

推荐答案

嗯,这取决于如何 DropDownItems.Count 实现 - 但坦率地说是的可能的是一个简单的现场支持的特性。 ..这将使第一个代码一样快的第二位,但的可读性更强

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.

先可读性 - 衡量业绩和微仅-optimize必要。

Readability first - then measure performance and micro-optimize only where necessary.

如果可能的话,虽然...又喜欢的foreach 循环入手,可读性的理由。

Where possible, prefer a foreach loop to start with though... again, on grounds of readability.

即使你的的想使用一个临时变量,我会保持在循环本身简单,hoising计数出独立的变量。诚然,这意味着更大范围内,但它是简单的:

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.

这篇关于for循环优化 - 需要与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆