Does list.count physically iterate through the list to count it, or does it keep a pointer

后端 未结 5 1901
臣服心动
臣服心动 2021-01-11 12:55

I am stepping through a large list of object to do some stuff regarding said objects in the list.

During my iteration, I will remove some objects from the list depen

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 13:58

    You tagged your question with both vb.net and c#, so in reply to "If .net physically re-iterates through the list, I may just as well keep a counter on my own iteration through the list, and save the overhead?"

    If your iteration is with a For i = first To last then VB.NET will evaluate first and last when it enters the loop:

    Dim first As Integer = 1
    Dim last As Integer = 3
    For i = first To last
        Console.Write(i.ToString() & " ")
        last = -99
    Next
    

    outputs: 1 2 3

    If you do the equivalent in C#, first and last are evaluated on every iteration:

    int first = 1;
    int last = 1;
    for (int i = first; i <= last; i++)
    {
        Console.Write(i.ToString() + " ");
        last = -99;
    }
    

    outputs: 1

    If your .Count() function/property is expensive to evaluate and/or you don't want it to be re-evaluated on each iteration (for some other reason), then in C# you could assign it to a temporary variable.

提交回复
热议问题