Is Array.Copy() faster than for loop, for 2D arrays?

前端 未结 3 1212
清酒与你
清酒与你 2021-01-18 09:14

I recently changed

        this.FieldValues = new object[2, fieldValues.GetUpperBound(1) + 1];
        for (int i = 0; i < FieldCount; i++)            
           


        
3条回答
  •  无人共我
    2021-01-18 09:49

    In your particular example, there is a factor that might (in theory) indicate the for loop is faster.

    Array.Copy is a O(n) operation while your for loop is O(n/2), where n is the total size of you matrix.

    Array.Copy needs to loop trough all the elements in your two-dimensional array because:

    When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end to end. For example, if an array has three rows (or columns) with four elements each, copying six elements from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column).

提交回复
热议问题