C# DynamicObject vs Dictionary性能,还是更快?

C# DynamicObject vs Dictionary性能,还是更快?,c#,performance,dynamic,dictionary,C#,Performance,Dynamic,Dictionary,我想知道在调用dynamicObject时,DLR或CLR是否进行了任何性能优化 给定代码类似于: var dictionary = new dictionary<string,string>() dictionary.add("hello","foo"); dynamic bag = new ..DynamicObject.. bag.hello = "foo"; //Are there any thread safety benefits, or performance diff

我想知道在调用dynamicObject时,DLR或CLR是否进行了任何性能优化

给定代码类似于:

var dictionary = new dictionary<string,string>()
dictionary.add("hello","foo");
dynamic bag = new ..DynamicObject..
bag.hello = "foo";
//Are there any thread safety benefits, or performance differences between making
//many calls to :
var x = dictionary["hello"];
var y = bag.hello;
下面是Foo.DictionaryBag'1的实现。。。。召唤

type DictionaryBag<'TKey when 'TKey:equality> ()=
    let bag = ConcurrentDictionary<System.Type,IDictionary>()
    ... snip ...
    /// returns a tuple of (Found * 'TValue) where the Key = (key * typeof<'TValue>)
    member this.TryGetValue<'TValue> (key:'TKey) =
            let found, innerCollection = bag.TryGetValue(typeof<'TValue>)    
            if found then
                let ic = innerCollection :?> ConcurrentDictionary<'TKey,'TValue> // Cast as the type we know it has to be
                let f, o = ic.TryGetValue key           // try to pull value out of inner dictionary
                (f,o)                                   // return what we found
            else
                (false, Unchecked.defaultof<'TValue>)   // if we didn't have an inner collection, then return (false and default<T>)
类型字典bag()=
let bag=ConcurrentDictionary()
... 剪
///返回(Found*'TValue)的元组,其中Key=(Key*typeof(Key:'TKey)=
let found,innerCollection=bag.TryGetValue(typeof)//如果没有内部集合,则返回(false和默认值)

…因此,您可以看到,当74%的分析时间都用在上述方法中时,字典性能是一个问题。

动态对象永远不会比字典更快。
动态对象执行其需要执行的操作时会发生多个调度。这是因为它可以重新分配给不同类型的comp在操作之间完全不同。这听起来像是预优化。通常,我担心的是可维护性而不是性能,因为通常情况下,您建议的速度差异很少是一个问题。遗憾的是,我每秒从当前字典中提取值超过20 mil次。我真的想确保在.net中没有可能更快的方法来获取val已在运行时指定的ues。@ErikPhilips更新了问题,其中包含关于预处理的部分-optimization@SimonWhitehead这不完全正确。如果类型和成员名称是静态的,则DLR生成的优化代码根本不需要字典查找。这有点像现代JS引擎。
type DictionaryBag<'TKey when 'TKey:equality> ()=
    let bag = ConcurrentDictionary<System.Type,IDictionary>()
    ... snip ...
    /// returns a tuple of (Found * 'TValue) where the Key = (key * typeof<'TValue>)
    member this.TryGetValue<'TValue> (key:'TKey) =
            let found, innerCollection = bag.TryGetValue(typeof<'TValue>)    
            if found then
                let ic = innerCollection :?> ConcurrentDictionary<'TKey,'TValue> // Cast as the type we know it has to be
                let f, o = ic.TryGetValue key           // try to pull value out of inner dictionary
                (f,o)                                   // return what we found
            else
                (false, Unchecked.defaultof<'TValue>)   // if we didn't have an inner collection, then return (false and default<T>)