检测不可变的高性能方法? [英] Performant way to detect immutables?

查看:55
本文介绍了检测不可变的高性能方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实用程序,旨在在系统中传递对象.因为它是一个多线程环境,所以该实用程序会对其传递的每个对象进行深层复制,以防止出现任何线程安全问题.我正在努力将系统转换为使用不可变对象,以消除对此副本的需要.我想知道检测对象不可变的最佳(最快)方法是什么?

I have a utility that is designed to pass objects around our system. Because it is a multithreaded environment, the utility makes a deep copy of each object it passes to prevent any thread safety issues. I'm working on transitioning our system to use immutable objects to eliminate the need for this copy. I'm wonder what is the best (fastest) way to detect that the object is immutable?

我的第一个想法就是选择我们放置在所有不可变对象上的属性(MessageAttribute).正如您从下面的性能概况中所看到的,它受到了很大的打击(执行时间是我所有其他检查的大约10倍).

My first thought was to just to pick up on the attribute that we put on all our immutable objects (MessageAttribute). As you can see from the performance profile below, it takes quite a hit (roughly 10x the time to execute as all my other checks).

我还能如何检测经过的不可变对象?我可以做一个typeof()比较,它看起来性能更高,但这似乎很笨拙,而且随着我们一直添加更多不可变项而难以维持.

How else can I detect my immutables passing through? I can just do a typeof() comparison, which appears way more performant, but this seems pretty unwieldy, and it will be hell to maintain as we add more immutables all the time.

编辑:我忘了提及布尔值是为了进行概要分析而重构为变量的,实际上,结果的表达式存储在isDefined中实际上是在语句,因此命中率比此概要文件中显示的命中率低约10倍(不过,我更关注平均执行时间,而不是绝对执行时间).

I forgot to mention that the boolean values are refactored out into variables for the purpose of profiling, in reality, the expressions who's result is stored in isDefined is actually in the else if statement, so would be hit about 10x less that shown in this profile (I'm more concerned with the average execution time than the absolute execution time though).

推荐答案

我最终实现了一个哈希集,该哈希集在静态构造函数中初始化,并获得了我想要传递的所有类型.

I ended up implementing a Hash set that is initialized in the static constructor and gets all the type I want to pass trough.

private static HashSet<Type> m_PassableTypes; // 


static SynthesisExtensions() { // 
    m_PassableTypes = new HashSet<Type>();
    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach (Type type in assembly.GetTypes()) {
            if (type.IsValueType || type == typeof (string) || type.Module.Name == "FSharp.Core.dll" ||
                type.IsDefined(typeof (MessageAttribute), false)) {
                m_PassableTypes.Add(type);
            }
        }
    }
}

这使我能够执行一个非常快速的HashSet查找,这会提高性能.

This allows me to then perform a really fast HashSet look up which is way more performant.

    Type type = instance.GetType();

    if (m_PassableTypes.Contains(type)) {
        // cache the self-reference
        referenceCache.Add(instance, instance);
        // return the value itself
        return instance;
    }

感谢所有帮助!我欢迎对此解决方案有任何想法

Thanks for all the help! I'd welcome any thoughts on this solution

这篇关于检测不可变的高性能方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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