[英]Difference between list.Count > 0 and list.Count != 0
我有事情清單。 list.Count > 0
和list.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 != 0
和list.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 > 0
和list.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
如您所見, je
, jg
或jmp
命令幾乎是最原子的命令,可能在以前的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.