English 中文(简体)
在C#中,在使用清单<T>时,没收不动产是否好,或者财产是否足够快?
原标题:In C#, when using List<T>, is it good to cache the Count property, or is the property fast enough?
  • 时间:2010-09-08 10:01:55
  •  标签:
  • c#

换言之,如果是的话,以下几个方面会更快?

List<MyClass> myList;
...
...
f或each (Whatever whatever in SomeOtherLongList)
{
  ...
  if (i < myList.Count)
  {
    ...
  }
}

List<MyClass> myList;
...
...
int listCount = myList.Count;
f或each (Whatever whatever in SomeOtherLongList)
{
  ...
  if (i < listCount)
  {
    ...
  }
}

感谢:

最佳回答

<代码>Count只是一种 in。 当你问其价值时,它会立即计算。 它预估了时间,因此也照此。 备选案文1更可读:

问题回答

<代码>List<T>s>确实没有必要加以扣押,因为它只是简单的财产。

但是,可在任何<代码>上使用的<代码>Count(>推广方法>。 可以用数字表示的非常昂贵,因为它可能需要列举整个顺序,以便加以计算(关于它只是使用该财产,但列举的是任何其他情况)。 另外,如果你需要知道计算是否为零,则最好采用>推广方法。

你们可以通过反省来审视“数字”的执行情况:

public int Count
{
    get
    {
        return this._size;
    }
}

如我们能够看到的那样,<代码>Count<>/code>只是归还该成员的财产_size,该财产在增加/从名单上删除:

public void Add(T item)
{
    if (this._size == this._items.Length)
    {
        this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size++] = item;
    this._version++;
}

public void RemoveAt(int index)
{
    if (index >= this._size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException();
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this._items, index + 1, this._items, index, this._size - index);
    }
    this._items[this._size] = default(T);
    this._version++;
}

因此,显然没有必要扣押财产。

b/c 即便只是一个变数,你节省了这一职能,也要求得到计票。

由于彩票的价值可能发生变化,编辑们赢得了取消这些功能的号召,因为它可能改变法典的语义。

第一是更可读和更好的选择,有<条码>没有在(listCount)中保存。

两者都取得了任何成绩。

一俟你制定名单,即自动确定名单。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签