What would be your reason not to write
list.Count.Equals(0)
when you probably write
list.Count == 0
Is there a technical/semantical reason?
What would be your reason not to write
list.Count.Equals(0)
when you probably write
list.Count == 0
Is there a technical/semantical reason?
I think there is no difference between two statements for this specific case. Since you are checking the equality of int
values; ==
operator and Equals
do exactly the same operation.
But for some other cases, for example for the following case, they may return different values;
Double.NaN == Double.NaN // is false
Double.NaN.Equals(Double.NaN) // is true
Generally, for value types you may go with ==
; but if it is a reference type, better to go with Equals
.
For int
the disassembly of a sample is displayed below; the generated assembly codes differ, so the performace is expected to differ;
int a = 10;
00000080 mov dword ptr [ebp-40h],0Ah
int b = 9;
00000087 mov dword ptr [ebp-44h],9
bool x = a == b;
0000008e mov eax,dword ptr [ebp-40h]
00000091 cmp eax,dword ptr [ebp-44h]
00000094 sete al
00000097 movzx eax,al
0000009a mov dword ptr [ebp-48h],eax
bool y = a.Equals(b);
0000009d lea ecx,[ebp-40h]
000000a0 mov edx,dword ptr [ebp-44h]
000000a3 call 6B8803C0
000000a8 mov dword ptr [ebp-60h],eax
000000ab movzx eax,byte ptr [ebp-60h]
000000af mov dword ptr [ebp-4Ch],eax
The two main reasons are
list.Count == 0 is easier to read (most important)
list.Count.Equals(0) is slower
list.Count == 0
has better readability and its shorter imo. If performance is negligible, always go with whats more readable and displays the intention the clearest way.
As for technical reasons: If you compare the two generated IL sequences.
IL_0029: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count()
IL_002e: stloc.s CS$0$0001
IL_0030: ldloca.s CS$0$0001
IL_0032: ldc.i4.0
IL_0033: call instance bool [mscorlib]System.Int32::Equals(int32)
// Equals(obj int) internally uses the method this == obj;
vs.
IL_007f: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count()
IL_0084: ldc.i4.0
IL_0085: ceq
one could argue that the == operator is faster because it uses less instructions, noone really knows how it gets optimized though.
Running a quick benchmark with JIT warmup and different sequences on which is called first, you'll notice that (At least on my machine) on an iteration over 100000000 elements, == is about 25 ms faster.
I think more readable would be
if (list.IsEmpty()) { ... }
I'm not a C# expert, so you better check here Recommended way to check if a sequence is empty how to make it work.