c#:这段代码会得到优化吗?
我正在审查第三方外包公司提供给我们的一些代码,并遇到了这个小宝石:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,正如您通过 Reflector 发现的那样,C# 编译器不会对其进行优化。 JIT 编译器是否会这样做是另一个问题。但是,我猜答案几乎肯定是否定的。
为什么?因为 JIT 编译器不知道
IndexOf
是一个无聊的方法。换句话说,据 JIT 编译器所知,string.IndexOf
可以定义为显然,在这种情况下优化该行会很糟糕。
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 asObviously, in that case optimizing out that line would be bad.
编译器如何知道
IndexOf
没有副作用?所以基本上不会,它不会对其进行优化。
How would the compiler know that
IndexOf
had no side-effects?So basically no, it's not going to optimize it out.
不,它不会被优化。
另一方面,它的开销非常小。与 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.