为什么“返回数组的属性容易导致代码效率低下”?

发布于 2024-09-11 02:08:32 字数 383 浏览 9 评论 0原文

我有一段处理数据库中存储的客户的代码。有一个对象 Customer,除其他外,它具有两个 byte[] 类型的属性:一个属性用于密码盐,第二个属性用于密码哈希。

使用 FxCop 检查代码,我发现它抱怨(CA1819性能规则):

“返回数组的属性容易导致代码效率低下。请考虑使用集合或将其设为方法。有关详细信息,请参阅设计指南。”

并建议:

“更改‘Customer.PasswordHash’以返回集合或使其成为方法。”

我真的不明白,我所做的代码效率低下是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尽揽少女心 2024-09-18 02:08:32

问题是数组总是是可变的。这意味着如果没有以下任一方法,您就无法从方法中返回一个:

  • 允许调用者弄乱您的内部状态
  • 首先创建副本

如果您使用集合,则可以在实际集合周围创建一个只读包装器,然后返回 -这可以便宜得多。或者,如果将其更改为会降低调用速度的期望的方法。

当然,如果您对调用者改变您的数据感到满意,那么数组就可以正常工作......

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文