加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#Foreach优化与反射

发布时间:2020-12-16 09:59:10 所属栏目:百科 来源:网络整理
导读:基本上,这个代码段是: // Get these once,create list,re-use same listvar prodType = products.GetType();var fieldInfList = prodType.GetFields();var propInfList = prodType.GetProperties();foreach (var p in products){ foreach (var fieldInf in
基本上,这个代码段是:

// Get these once,create list,re-use same list
var prodType = products.GetType();
var fieldInfList = prodType.GetFields();
var propInfList = prodType.GetProperties();

foreach (var p in products)
{
    foreach (var fieldInf in fieldInfList)
    {
        fieldInf.SetValue(this,fieldInf.GetValue(p));
    }
    foreach (var propInf in propInfList)
    {
        propInf.SetValue(this,propInf.GetValue(p));
    }
}

比这更快:

foreach (var p in products)
{
    foreach (var fieldInf in products.GetType().GetFields())
    {
        fieldInf.SetValue(this,fieldInf.GetValue(p));
    }
    foreach (var propInf in products.GetType().GetProperties())
    {
        propInf.SetValue(this,propInf.GetValue(p));
    }
}

…?

我的想法是,对于第二个块,每个循环将执行再次检查对象的工作,而第一个将具有将在每个循环中持续存在的列表.

与线路类似

var prodType = products.GetType();

该类型只会被检索一次.

或者编译器/ .Net只是在第二个例子中重复使用相同的列表,而我不必做任何事情?如何将创建新列表的开销与重复获取对象属性进行比较?垃圾收集器是否会以不同的方式处理我创建的列表,导致它更长时间挂起?

任何答案或指向正确的方向非常感谢.

解决方法

Or does the compiler / .Net just re-use the same list in the second example without me having to do anything?

如果它知道Reflection API是幂等的,并且结果对象是观察纯的,它就可以做到.它不知道.此优化将无法完成.调用任何Reflection API都可以在理论上打印到控制台. JIT必须执行调用才能确定.

事实上,即使这样,它也不是一个安全的优化,因为Reflection API可能会抛出,只有在外部循环至少执行一次迭代时才会引发该异常.

是的,将列表分解将导致性能提升.

How do I compare the overhead of creating a new list with getting the object properties repeatedly?

不确定你的意思.测量.

Would the garbage collector treat my created list any differently causing it to hang around longer?

这对GC没有影响,因为属性列表很小(可能是几百个字节,具体取决于属性的数量).

将链表分解出来会导致该列表保持活动一小段时间,因为列表将保持活动状态直到外部循环完成(至少在CLR的当前实现中).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读