c#:这段代码会得到优化吗?

发布于 2024-10-05 20:59:53 字数 593 浏览 2 评论 0原文

我正在审查第三方外包公司提供给我们的一些代码,并遇到了这个小宝石:

try
{
    int i = strOriginalData.IndexOf("\r\n");
    ////System.Diagnostics..EventLog.WriteEntry("i", i.ToString());
}
catch (System.Exception ex)
{
    ////System.Diagnostics..EventLog.WriteEntry("ex", ex.Message);
}

我的问题是编译器会完全优化它吗?当我在 Reflector 中查看编译后的程序集时,它显示:

try
{
    i = this.strOriginalData.IndexOf("\r\n");
}
catch (Exception exception1)
{
    ex = exception1;
}

i 的声明已移至方法的顶部,并且 Exception 类型的附加声明也位于方法的顶部。

因此,由于这段代码实际上没有做任何事情,我想知道编译器是否足够聪明,可以看到这段代码什么都不做,并且可以优化它。

I was reviewing some code given to us by a third-party outsourcing firm and ran across this little gem:

try
{
    int i = strOriginalData.IndexOf("\r\n");
    ////System.Diagnostics..EventLog.WriteEntry("i", i.ToString());
}
catch (System.Exception ex)
{
    ////System.Diagnostics..EventLog.WriteEntry("ex", ex.Message);
}

My question is will the compiler completely optimize this out? When I look at the compiled assembly in Reflector, it shows this:

try
{
    i = this.strOriginalData.IndexOf("\r\n");
}
catch (Exception exception1)
{
    ex = exception1;
}

The declaration for i has been moved to the top of the method, and additional declaration of type Exception is at the top of the method also.

So, since this code doesn't really do anything, I was wondering if the compiler is smart enough to see that this code does nothing and can optimize it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁对谁错谁最难过 2024-10-12 20:59:53

因此,正如您通过 Reflector 发现的那样,C# 编译器不会对其进行优化。 JIT 编译器是否会这样做是另一个问题。但是,我猜答案几乎肯定是否定的。

为什么?因为 JIT 编译器不知道 IndexOf 是一个无聊的方法。换句话说,据 JIT 编译器所知,string.IndexOf 可以定义为

public int IndexOf()
{
   CallAWebService();
}

显然,在这种情况下优化该行会很糟糕。

So, as you've found via Reflector, the C# compiler will not optimize it out. Whether the JIT compiler will is another question. But, I would guess the answer is almost certainly not.

Why? Because the JIT compiler doesn't know that IndexOf is a boring method. In other words, as far as the JIT compiler knows, string.IndexOf could be defined as

public int IndexOf()
{
   CallAWebService();
}

Obviously, in that case optimizing out that line would be bad.

最丧也最甜 2024-10-12 20:59:53

编译器如何知道 IndexOf 没有副作用?

所以基本上不会,它不会对其进行优化。

How would the compiler know that IndexOf had no side-effects?

So basically no, it's not going to optimize it out.

勿忘心安 2024-10-12 20:59:53

不,它不会被优化。

另一方面,它的开销非常小。与 string.IndexOf() 设置 catch 块的成本相比,可以忽略不计。

如果有例外,就会产生成本,但这不太可能。

No, it won't be optimized out.

On the other hand, it is a very small overhead. Compared to the cost of string.IndexOf() setting up the catch block is negligible.

There would be a cost if there ever was an exception, but that's not likely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文