在设置为空之前检查是否为空? [英] Check if null before set to null?
问题描述
我们是否应该在将变量设置为空之前检查变量是否为空?
Should we check if variable is null before setting it to null?
if (MyBills != null)
{
MyBills = null;
}
例如,在 Java 相关问题性能影响很小.在 C# 中是这种情况吗?其他影响?
For, example, in a Java related question the performance implications are minimal. Is this the case in C#? Other implications?
我创建了以下代码进行测试:
I've created the following code to test:
var watch = System.Diagnostics.Stopwatch.StartNew();
int iterations = int.MaxValue;
List<int> myBills= null;
for (var i = 0; i < iterations; i++)
{
if (myBills!= null)
{
myBills = null;
}
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs);
在带有和不带有 if (myList != null)
的 rextester 上运行它结果如下:
Running it on rextester with and without the if (myList != null)
the results are as following:
With check Without check
988 941
938 1021
953 987
998 973
1004 1031
Average
976.2 990.6
因此,即使在非受控环境中对其进行测试,其性能影响也无关紧要.
So, even testing it in a non-controlled environment, the performance implications are irrelevant.
推荐答案
不,没什么用.可能检查变量是否为空与多次将其设置为空一样昂贵.
No, there is not much use. Probably checking the variable being null or not is just as expensive as setting it to null one time too many.
如果它是一个属性,背后有额外的逻辑,那么之前测试它可能是有意义的,但这实际上应该是属性中逻辑的责任,而不是您的代码.
If it was a property, with additional logic behind it, it could make sense to test it before, but that should actually be the responsibility of the logic in the property, not your code.
这篇关于在设置为空之前检查是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!