请问C#编译器优化的foreach块时,其内容有Conditional属性? [英] Does the C# compiler optimize foreach blocks when its contents have the Conditional attribute?

查看:111
本文介绍了请问C#编译器优化的foreach块时,其内容有Conditional属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写在工作中的一些调试代码,我想知道如果我在做什么可能会伤害性能与否。

I'm writing some debug code at work, and I'm wondering if what I'm doing might hurt performance or not.

让我们的代码

foreach (var item in aCollection)
    Debug.WriteLine(item.Name);



我知道,调试类使用条件属性,以避免在释放模式编译(或当DEBUG为未定义),但这样做最终成为徒劳/空迭代在发布模式下进行编译时,或将其编译器?

I know that the Debug class uses the Conditional attribute to avoid compilation in release mode (or whenever DEBUG is undefined), but would this end up as a futile/empty iteration when compiled in release mode or would it be optimized by the compiler?

推荐答案

C#编译器不会优化掉枚举,因为枚举一个集合的行为可能产生的副作用:

The C# compiler will not optimize away the enumeration because the act of enumerating over a collection may produce side effects:


  1. 在数组的情况下,索引的行为到数组意味着副作用(和C#编译器重写的foreach 数组遍历到索引循环)。

  2. 对于其他的收藏,调用的GetEnumerator()的MoveNext()暗示的副作用。

  1. In the case of an array, the act of indexing into the array implies a side effect (and the C# compiler rewrites foreach loops over arrays into indexing loops).
  2. For other collections, the calls to GetEnumerator() and MoveNext() imply side effects.

在这两种情况下,潜在的非关联化副作用。

In both cases, the potential null dereference is a side effect.

当调用 [有条件] 方法,只有方法调用和其正式参数将被从编译的代码省略。请注意,即使参数的副作用的将被省略。但是,没有的周围代码的将被省略。

When invoking a [Conditional] method, only the method call and its formal arguments will be omitted from the compiled code. Note that even arguments with side effects would be omitted. However, no surrounding code would be omitted.

我自己的测试表明,即使增加一个明确的检查将不会哄C#编译器将优化掉枚举,即使是一个简单的数组。

My own tests show that even adding an explicit null check will not coax the C# compiler into optimizing away the enumeration, even for a simple array.

无论在 JIT编译器优的走枚举代码是另一个问题。它可能,如果能够证明该集合总是非 - ,有没有其他有意义的副作用。在JIT的可能的足够复杂到数组做到这一点;我不会赌,虽然。如果添加的开销担心你,将作为@pid建议一个#如果区域内的枚举代码。

Whether the JIT compiler optimizes away the enumeration code is another question. It might, if it can prove that the collection is always non-null and that there are no other meaningful side effects. The JIT might be sophisticated enough to do this for arrays; I wouldn't bet on it, though. If the added overhead concerns you, place the enumeration code within an #if region as @pid suggests.

这篇关于请问C#编译器优化的foreach块时,其内容有Conditional属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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