As explained by everyone, functionally there's no difference between list.Count != 0
and list.Count > 0
as list.Count can not be < 0.
I did a quick test, and it shows both != 0
and > 0
are almost equally fast (and that's super fast). Linq's list.Any()
is NOT as fast though!
Here's the test code (comparing 100000 times to magnify the difference)
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();
}
And it shows:
Time taken by != : 0
Time taken by > : 0
Time taken by Any() : 10
list
, and the type oflist.Count
. – Cocteau