In C#, Is it slower to reference an array variable?

后端 未结 5 2140
轮回少年
轮回少年 2020-12-18 18:02

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]
}
         


        
5条回答
  •  太阳男子
    2020-12-18 18:50

    The compiler can only perform common subexpression optimization here if it can prove that the array isn't accessed by other threads or any methods (including delegates) called inside the loop, it might be better to create the local copy yourself.

    But readability should be your main concern, unless this loop executes a huge number of times.

    All of this is also true in C and C++ -- indexing into an array will be slower than accessing a local variable.

    As a side note, your suggested optimization is no good: value is a keyword, choose a different variable name.

提交回复
热议问题