Why “Properties that return arrays are prone to co

2019-04-21 17:47发布

问题:

I have a piece of code which deals with customers stored in database. There is an object Customer, and it has, among other, two properties of type byte[]: one property for password salt, the second one for password hash.

Checking the code with FxCop, I see that it complains (CA1819, Performance Rules) that:

"Properties that return arrays are prone to code inefficiencies. Consider using a collection or making this a method. See the design guidelines for more information."

and suggests:

"Change 'Customer.PasswordHash' to return a collection or make it a method."

I don't really understand, what is the code inefficiency in what I'm doing?

回答1:

The problem is that arrays are always mutable. That means you can't return one from a method without either:

  • Allowing the caller to mess up your internal state
  • Creating a copy first

If you use a collection, you can create a read only wrapper around the real collection instead, and return that - and that can be considerably cheaper. Alternatively, if you change it to a method that will lower the expectation that it will be very quick to call.

Of course, if you're happy with callers mutating your data, then an array will work fine...