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

前端 未结 3 1241
清酒与你
清酒与你 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:43

    The way .Net works under the hood, I'd guess that in an optimized situation, Array.Copy would avoid bounds checking.

    If you do a loop on any type of collection, by default the CLR will check to make sure you're not passing the end of the collection, and then the JIT will either have to do a runtime assessment or emit code that doesn't need checking. (check the article in my comment for better details of this)

    You can modify this behaviour, but generally you don't save that much. Unless you're in a tightly executed inner loop where every millisecond counts, that is.

    If the Array is large, I'd use Array.Copy, if it's small, either should perform the same.

    I do think it's bounds checking that's creating the different results for you though.

提交回复
热议问题