Should array length be stored into a local variable in C#?

Is there any impact in execution performance because of using array.Length directly as for exit condition? Which one of following methods will excute faster?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public int WithoutVariable() {
    int sum = 0;
    for (int i = 0; i < array.Length; i++) {
        sum += array[i];
    }
    return sum;
}

public int WithVariable() {
    int sum = 0;
    int length = array.Length;
    for (int i = 0; i < length; i++) {
        sum += array[i];
    }
    return sum;
}

Dmitry Yudakov concludes through digging into the IL code generated by JIT compiler for both methods:

… both methods will compile into the exact same code, but the first one is written faster, even though there isn’t any benefit in terms of execution time.

0 Comments