为什么“返回数组的属性容易导致代码效率低下"? [英] Why "Properties that return arrays are prone to code inefficiencies"?

查看:88
本文介绍了为什么“返回数组的属性容易导致代码效率低下"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

使用FxCop检查代码,我发现它抱怨( CA1819 Performance Rules ):

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

并建议:

更改"Customer.PasswordHash"以返回集合或使其成为方法."

"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?

推荐答案

问题是数组总是 可变的.这意味着您不能在没有一个方法的情况下从方法中返回一个:

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

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

如果使用集合,则可以围绕实际集合创建只读包装,然后将其返回-这样可以便宜得多.另外,如果将其更改为可以降低调用速度的期望的方法,则可以降低调用速度.

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

这篇关于为什么“返回数组的属性容易导致代码效率低下"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆