Joan Venge
Joan Venge

Reputation: 330892

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 VertexElement [ ] 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?

Upvotes: 3

Views: 152

Answers (2)

TrueWill
TrueWill

Reputation: 25523

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.

Upvotes: 1

InBetween
InBetween

Reputation: 32740

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.

Upvotes: 3

Related Questions