空试验与尝试捕捉 [英] null test versus try catch
问题描述
有没有人有与在尝试捕捉封装代码进行测试空指标?
Does anyone have metrics on performing null test versus wrapping code in a try catch?
我怀疑是空的测试是更有效的,但我不。有什么经验数据
I suspect that the null test is much more efficient, but I don't have any empirical data.
环境是C#/。NET 3.x和代码比较:
The environment is C#/.net 3.x and the code comparison is:
Dude x = (Dude)Session["xxxx"];
x = x== null ? new Dude(): x;
与
versus
Dude x = null;
try {
x = (Dude)Session["xxxx"];
x.something();
} catch {
x = new Dude();
}
有什么优势,在尝试捕捉包装?
are there any advantages to wrapping in try catch?
推荐答案
如果null是一个可能的预期值,则测试空。如果你不喜欢空试验和有一个默认值,可以使用空coelescing操作员设置的默认值:
If null is a possible expected value, then test for null. If you don't like the null test and have a default value, you can use the null coelescing operator to set the default value:
// value is (Dude)Session["xxxx"] if not null, otherwise it's a new object.
Dude x = (Dude)Session["xxxx"] ?? new Dude();
保存try / catch语句的例外(真正的突发事件)。
Save try/catch for Exceptions (truly unexpected events).
这篇关于空试验与尝试捕捉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!