Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Properties that return arrays are prone to code inefficiencies"?

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?

like image 938
Arseni Mourzenko Avatar asked Jul 24 '10 06:07

Arseni Mourzenko


1 Answers

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...

like image 113
Jon Skeet Avatar answered Sep 19 '22 06:09

Jon Skeet