gpt4 book ai didi

c# - 避免数组重复

转载 作者:行者123 更新时间:2023-11-30 19:52:09 25 4
gpt4 key购买 nike

根据 [MSDN:数组使用指南]( http://msdn.microsoft.com/en-us/library/k2604h5s(VS.71).aspx) :

数组值属性

You should use collections to avoid code inefficiencies. In the following code example, each call to the myObj property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

[Visual Basic]

Dim i As Integer
For i = 0 To obj.myObj.Count - 1
DoSomething(obj.myObj(i))
Next i

[C#]
for (int i = 0; i < obj.myObj.Count; i++)
DoSomething(obj.myObj[i]);

除了从 myObj[] 更改为 ICollection myObj 之外,您还有什么建议?刚刚意识到我当前的应用程序正在泄漏内存:(

谢谢;

编辑:强制 C# 传递带 ref 的引用(安全性除外)会提高性能和/或内存使用率吗?

最佳答案

不,这不是泄漏内存 - 它只是让垃圾收集器比它可能更努力地工作。实际上,MSDN 文章有点误导:如果该属性在每次调用时都创建一个新的 collection,那么它和数组一样糟糕(内存方面)。或许更糟的是,由于大多数集合实现通常规模过大。

如果您知道某个方法/属性确实有效,您始终可以最大限度地减少调用次数:

var arr = obj.myObj; // var since I don't know the type!
for (int i = 0; i < arr.Length; i++) {
DoSomething(arr[i]);
}

或者更简单,使用foreach:

foreach(var value in obj.myObj) {
DoSomething(value);
}

这两种方法都只调用属性一次。第二个是更清晰的 IMO。

其他想法;将其命名为方法!即 obj.SomeMethod() - 这设定了它确实有效的预期,并避免了不受欢迎的 obj.Foo != obj.Foo(数组就是这种情况) .

最后,Eric Lippert 有一个很好的 article on this subject .

关于c# - 避免数组重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com