丢弃运算符的性能优势 [英] Performance advantage of discard operator

查看:55
本文介绍了丢弃运算符的性能优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的 C# 应用程序中有这个:

Lets say I have this in my C# app:

try{
    Somethrowingmethod();
}catch(Exception ex){
    throw new Exception("oops");
}

如果我保持代码不变,编译器会(理所当然地)抱怨我声明了 ex 但没有使用它.

If I keep my code as it is, the compiler will (rightfully so) complain about me declaring ex but no using it.

所以我应该这样做:

try{
    Somethrowingmethod();
}catch(Exception _){
    throw new Exception("oops");
}

我的问题是,一旦我这样做了,性能会有提升吗?

还是只是为了干净的代码实践?

Or is it only for a clean code practice?

推荐答案

您的问题有缺陷,因为您的示例不涉及丢弃.相反,它将 Exception 变量命名为 _ 并且仍然应该为未使用的变量发出相同的警告.看到在警告和<代码> 此SharpLab 示例和外表.locals init 生成的 IL.

Your question is flawed as your example does not involve discards. Instead, it names the Exception variable _ and should still emit the same warning for the unused variable. See this SharpLab example and look at the warning and the .locals init of the generated IL.

.locals init (
  [0] class [System.Private.CoreLib]System.Exception
)

丢弃"异常的正确方法是仅捕获类型:

The proper way to "discard" an exception is to catch the type only:

try {
  DoSomething();
} catch (Exception) {
  //... 
} 

这并没有声明一个局部变量,您可以在上面的链接中通过擦除 _ 并查看更新的 .locals init 部分来验证它(提示:它是现在没了).

This does not declare a local variable which you can verify at the above link by just erasing the _ and looking at the updated .locals init section (hint: it's gone now).

由于这是捕获基本异常类型,因此您也可以将其重写为:

Since this is catching the base exception type you could also rewrite it as:

try {
  DoSomething();
} catch {
  //... 
} 

但是请注意,通常捕获所有/捕获基本的 Exception 类型是一个坏主意.

Note however, that it is generally a bad idea to catch-all / catch the base Exception type.

不过回到您最初的询问:在任何这些场景中都没有涉及性能提升.充其量一个变量被省略了,但一个真正的丢弃只是语法糖,变量仍然被声明.这段代码:

Back to your original inquiry though: there's no performance gain involved in any of these scenarios. At best a variable is elided, but a true discard is just syntactic sugar and a variable is still declared. This code:

int.TryParse("1", out _);

仍然涉及int类型的局部变量.你可以看到,通过查看相同的IL 的部分.

still involves a local variable of type int. You can see that by viewing the same section of the IL.

.locals init (
  [0] int32
)

但同样,没有性能提升.

But again, there's no performance gain.

这篇关于丢弃运算符的性能优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆