在C#中,它是慢引用数组变量? [英] In C#, Is it slower to reference an array variable?
问题描述
我有一个整数数组,而我通过他们的循环:
I've got an array of integers, and I'm looping through them:
for (int i = 0; i < data.Length; i++)
{
// do a lot of stuff here using data[i]
}
如果我做的:
for (int i = 0; i < data.Length; i++)
{
int value = data[i];
// do a lot of stuff with value instead of data[i]
}
有任何性能收益/损失?
Is there any performance gain/loss?
这是我的理解,C / C ++数组元素直接访问,即整数n元素数组的长度为n * sizeof的(INT)一个连续的内存块,并且该程序访问元素我做的东西像*数据[I] = *数据[0] +(I *的sizeof(int)的)。 (请原谅我滥用的符号,但你明白我的意思。)
From my understanding, C/C++ array elements are accessed directly, i.e. an n-element array of integers has a contiguous memory block of length n * sizeof(int), and the program access element i by doing something like *data[i] = *data[0] + (i * sizeof(int)). (Please excuse my abuse of notation, but you get what I mean.)
因此,这意味着C / C ++应该没有业绩收益/损失引用数组变量。
So this means C/C++ should have no performance gain/loss for referencing array variables.
那么C#? C#有一堆像data.Length,data.IsSynchronized,data.GetLowerBound(),data.GetEnumerator()。
What about C#? C# has a bunch of extra overhead like data.Length, data.IsSynchronized, data.GetLowerBound(), data.GetEnumerator().
显然,一个C#阵列是不一样的一个C / C ++数组
Clearly, a C# array is not the same as a C/C++ array.
那么,有什么评价呢?如果我存储int值=数据[i]和与价值的工作,或者是有没有性能影响?
So what's the verdict? Should I store int value = data[i] and work with value, or is there no performance impact?
推荐答案
是,还有一个性能损失,由于边界检查每个访问阵列。
Yes, there is a performance loss due to the bounds check for every access to the array.
否,您很可能并不需要担心。
No, you most likely don't need to worry about it.
是的,你可以应存储的价值,并与价值的工作。不,这不是因为性能问题,而是因为它使code更具有可读性(恕我直言)。
Yes, you can should store the value and work with the value. No, this isn't because of the performance issue, but rather because it makes the code more readable (IMHO).
顺便说一句,JIT编译器的也许的优化了多余的检查,所以它并不意味着你就会得到在每次调用检查。无论哪种方式,它可能不是值得你花时间担心;只是用它,如果它原来是一个瓶颈,你可以随时回去,并使用不安全
块。
By the way, the JIT compiler might optimize out redundant checks, so it doesn't mean you'll actually get a check on every call. Either way, it's probably not worth your time to worry about it; just use it, and if it turns out to be a bottleneck you can always go back and use unsafe
blocks.
这篇关于在C#中,它是慢引用数组变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!