8

I've been reading tips about Javascript performance boosting and one tip said to cache all the variables (that don't change) in the loops comparer statement and I was wondering if this also applied to .NET.

Assuming I had a simple for loop, which one of the following would be faster or would they be the same?

No Cache:

for (int i = 0; i < someArray.Length; i++)
{

}

With Cache:

for (int i = 0, count = someArray.Length; i < count; i++)
{

}

According to the article "caching" the value of Length cuts out one operation in the loop because its faster to access local variables compared to accessing members of an object. Is it actually faster declaring a local variable compared to simply accessing the member? Does the compiler pick up on this and automatically cache the value? Is there any negatives in declaring a local variable over accessing the member?

Whilst speed is probably a key factor here, its not the only one. My next question would probably be which one is more efficient. Which uses less memory allocations? Which performs less stack manipulation? etc...

From comments, it seems accessing array lengths is pretty fast. Lets say I use an IList<> instead. Would caching the value of Count be faster than retrieving it each iteration?

4

4 に答える 4

-1

コードが高速になるとは思えませんが、実際には遅くなる可能性があります。配列の長さを取得するのは非常に安価であり (おそらく L1 ヒット)、事前に長さを計算すると、JIT の境界チェックの除去が台無しになる可能性があります。

C# では、array[i] の記述は、実際には次のように記述します。 if (i >= array.Length) throw...; 配列[i]

CLR の作成者は、不要な場合にこれらのチェックをなくす JIT の作成に多くの時間を費やしました。2 番目のスタイルでループを記述すると、CLR がチェックを排除できなくなる可能性があります。

于 2013-05-19T07:46:39.717 に答える