缓存对象的高效克隆 [英] Efficient cloning of cached objects

查看:245
本文介绍了缓存对象的高效克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有,其对数据对象进行比较,以确定该对象的一个​​版本比彼此不同的应用程序。我们的应用程序也做这些对象的某些范围的高速缓存,我们已经遇到了一点,当谈到做这些比较是性能问题,

We have an application that performs comparisons on data objects to determine if one version of the object is different than another. Our application also does some extensive caching of these objects, and we've run into a bit of a performance issue when it comes to doing these comparisons.

下面的工作流程:


  1. 数据第1项是在内存中当前的项目。这个项目最初从缓存中检索和深克隆(所有子对象,如字典等)。然后数据项1编辑,其属性被修改。

  2. 然后我们比较针对存储在缓存中的原始版本的对象。由于数据项1克隆及其属性改变,这些对象应该是不同的。

有几个问题在这里。

主要的问题是我们的深克隆的方法是非常昂贵的。我们评测的这对一个浅克隆,它是慢10倍。这是废话。下面是我们深clone方法:

The main issue is our deep clone method is very expensive. We profiled it against a shallow clone and it was 10x slower. That's crap. Here's our method to deep clone:

    public object Clone()    
    {
        using (var memStream = new MemoryStream())
        {
            var binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
            binaryFormatter.Serialize(memStream, this); 
            memStream.Seek(0, SeekOrigin.Begin);
            return binaryFormatter.Deserialize(memStream);
        }
    }

我们最初使用以下克隆:

We were initially using the following to clone:

public object Clone()
{
    return this.MemberwiseClone();
}

这是更好的性能,而是因为它确实浅克隆所有复杂的对象组成此对象的属性,诸如字典等,并没有进行克隆。对象仍然含有相同的附图因为这是在高速缓存的对象,因此该特性是在比较相同。

This was more performant, but because it does a shallow clone all the complex objects that were properties of this object, such as Dictionaries etc, were not cloned. The object would still contain the same reference as the object that was in the cache, therefore the properties would be the same upon comparison.

因此,没有人有一种有效的方法这样做对C#对象深克隆,将覆盖克隆整个对象图?

So, does anyone have an efficient way of doing a deep clone on C# objects that would cover cloning the entire object graph?

推荐答案

你不是要能够让您比通用二进制序列化更好,而不在需要被克隆的所有数据对象明确实施ICloneable。另一种可能的途径是反思,但你不会喜欢它或者,如果你正在寻找的表现。

You're not going to be able to get much better than your Generic Binary Serialization without Explicitly implementing ICloneable on all your data objects that need to be cloned. Another possible route is reflection, but you won't be happy with it either if you are searching for performance.

我会考虑的命中与ICloneable深拷贝和/或IComparable的对,如果对象是不同的......如果表现大的一个问题,你比较。

I would consider taking the hit with ICloneable for deep copy and/or IComparable for comparing if the objects are different ... if the performance is that big of an issue for you.

这篇关于缓存对象的高效克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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