我有一个List<int>
它从方法获取其值
List<int> items = GetIntegerStuff();
所以当前避免 NullReference 异常的代码如下所示
if (items == null)
{
items = new List<int>();
}
我已经将其更改为这个,因为我喜欢短代码 - 但我的高级开发人员说这很糟糕,因为如果有项目(大约 90% 的请求发生),整个列表将被分配,这对表现。这是真的吗?
items = items ?? new List<int>();
最佳答案
就您使用它的方式而言,两者在性能方面完全相同,因为它们编译为完全相同的东西。
测试代码:
static void NullCoalescing(List<int> a)
{
a = a ?? new List<int>();
Console.WriteLine(a);
}
static void IfStatement(List<int> a)
{
if(a == null) a = new List<int>();
Console.WriteLine(a);
}
编译为:
C.NullCoalescing(System.Collections.Generic.List`1<Int32>)
L0000: push rsi
L0001: sub rsp, 0x20
L0005: test rcx, rcx
L0008: jnz L0044
L000a: mov rcx, 0x7ffb92892a78
L0014: call 0x7ffb94712540
L0019: mov rsi, rax
L001c: mov ecx, 0x1
L0021: mov edx, 0x43
L0026: call 0x7ffb9487ff10
L002b: mov rdx, 0x2966e0ddef8
L0035: mov rdx, [rdx]
L0038: lea rcx, [rsi+0x8]
L003c: call 0x7ffb94713e70
L0041: mov rcx, rsi
L0044: call System.Console.WriteLine(System.Object)
L0049: nop
L004a: add rsp, 0x20
L004e: pop rsi
L004f: ret
C.IfStatement(System.Collections.Generic.List`1<Int32>)
L0000: push rsi
L0001: sub rsp, 0x20
L0005: test rcx, rcx
L0008: jnz L0044
L000a: mov rcx, 0x7ffb92892a78
L0014: call 0x7ffb94712540
L0019: mov rsi, rax
L001c: mov ecx, 0x1
L0021: mov edx, 0x43
L0026: call 0x7ffb9487ff10
L002b: mov rdx, 0x2966e0ddef8
L0035: mov rdx, [rdx]
L0038: lea rcx, [rsi+0x8]
L003c: call 0x7ffb94713e70
L0041: mov rcx, rsi
L0044: call System.Console.WriteLine(System.Object)
L0049: nop
L004a: add rsp, 0x20
L004e: pop rsi
L004f: ret
如您所见,它们编译后完全相同。
在这里查看:
关于c# - 检查 List<T> 是否为 null 时空合并运算符的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363292/