开发者

Array cloning on access?

I was reading XNA library code and inside the type VertexPositionColor, they supress the CA2105:ArrayFieldsShouldNotBeReadOnly message with the justification "The performance cost of cloning the array each time it is used is too great."

public struct VertexPositionColor
{
    public static readonly VertexE开发者_高级运维lement [ ] VertexElements;
}

But why would it be copied when it's used? This only happens for structs where the accessed property/field is a ValueType, right?


I guess they are justifying the fact that they are exposing an array field more than anything else and the underlying reason of why they are doing so is performance:

The alternative they probably had in mind was making the array field private with a property exposing an IEnumerable or returning a copy of the array each time the property was accesed.

EDIT. Edited the answer a little to make clearer what I was trying to say :p.


In most cases they'd be better off using Array.AsReadOnly and returning a generic ReadOnlyCollection. According to the documentation that's an O(1) operation.

In the current implementation callers can change the values in the array (modifying the static/global state directly).

One more reason to read Framework Design Guidelines - it gives you the reasons behind FxCop's recommendations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜