簡體   English   中英

list.Count> 0和list.Count!= 0之間的差異

[英]Difference between list.Count > 0 and list.Count != 0

我有事情清單。 list.Count > 0list.Count != 0之間有什么區別嗎? 還是這些代碼的性能差異?

if (list.Count > 0)
    // do some stuff

if (list.Count != 0)
    // do some stuff

注意: list.Count不能小於list.Count ..

實際上,這沒有什么區別,因為列表永遠不會少於0個項目,但是用於整數比較的==非常快,因此它可能比>快。 看起來更酷的方法是list.Any()

(這是通過列表假設的,您是指列表類型或任何內置的IEnumerable / Collection)

正如大家所解釋的那樣, list.Count != 0list.Count > 0作為list.Count在功能上沒有區別.Count不能小於0。

我做了一個快速測試,它顯示!= 0> 0 幾乎都一樣快(而且非常快)。 Linq的list.Any()那么快!

這是測試代碼(比較100000次以放大差異)

static List<object> GetBigObjectList()
{
    var list = new List<object>();
    for (int i = 0; i < 10000; i++)
    {
        list.Add(new object());
    }
    return list;
}

static void Main(string[] args)
{
    var myList = GetBigObjectList();
    var s1 = new Stopwatch();
    var s2 = new Stopwatch();
    var s3 = new Stopwatch();

    s1.Start();
    for (int i = 0; i < 100000; i++)
    {
        var isNotEqual = myList.Count != 0;
    }
    s1.Stop();

    s2.Start();
    for (int i = 0; i < 100000; i++)
    {
        var isGreaterThan = myList.Count > 0;
    }
    s2.Stop();

    s3.Start();
    for (int i = 0; i < 100000; i++)
    {
        var isAny = myList.Any();
    }
    s3.Stop();

    Console.WriteLine("Time taken by !=    : " + s1.ElapsedMilliseconds);
    Console.WriteLine("Time taken by >     : " + s2.ElapsedMilliseconds);
    Console.WriteLine("Time taken by Any() : " + s3.ElapsedMilliseconds);            
    Console.ReadLine();
}

它顯示:

!=花費的時間:0
花費的時間:: 0
Any()花費的時間:10

list.Count > 0list.Count != 0之間有什么區別嗎?

是。 第一個評估list.Count是否大於0 第二個評估它是否不等於0 “大於”和“不等於”是不同的東西。

我猜在CPU寄存器級別上,用於比較兩個數字的匯編命令將逐位檢查這些數字,並將激活一些條件標志以跳轉到指定的行。 例如:

cmp BL, BH     ; BL and BH are cpu registers
je EQUAL_Label       ; BL = BH
jg GREATER_Label     ; BL > BH
jmp LESS_Label       ; BL < BH

如您所見, jejgjmp命令幾乎是最原子的命令,可能在以前的cmp (比較)命令上起作用。 總之,我們可以說這些比較命令之間沒有顯着的性能差異。
祝好運

在這種特定情況下,兩者之間沒有典型的區別。 但是!=>0完全不同。 >0僅在count(條件表達式)大於0時執行,其中as !=當count(條件表達式)大於0且小於0

if (list.Count > 0)
{
  // Execute only when the count greater than 0
}
if (list.Count != 0)
{
  // Execute only when the count not equal to 0
}

我想如果ICollection.Count是uint類型,您將不會遇到這樣的問題。 請參閱“為什么ICollection.Count是int在某些類中,.NET為什么使用int而不是uint?

從可讀性的角度來看, list.Count != 0將導致思考Count是否可以為負數。 所以我更喜歡list.Count > 0 personaly。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM