2

我正在研究 C# 对象复制构造函数,其中一部分涉及将 KeyedCollection 的内容复制到新的 KeyedCollection 中。这是我目前实施的:

class MyKeyedCollection : KeyedCollection<uint, DataObject>
{
    protected override uint GetKeyForItem( DataObject do )
    {
        return do.Key;
    }
}

class MyObject
{
    private MyKeyedCollection kc;

    // Copy constructor
    public MyObject( MyObject that )
    {
        this.kc = new MyKeyedCollection();
        foreach ( DataObject do in that.kc )
        {
            this.kc.Add( do );
        }
    }
}

这是正确的——集合按预期复制。问题是它也有点慢。我猜问题是每个 .Add(do) 都需要对现有数据进行唯一性检查,即使我知道它来自保证唯一性的来源。

我怎样才能使这个复制构造函数尽可能快?

4

5 回答 5

3

我刚刚运行了一个测试,将 10,000,000 个项目添加到各种集合中,KeyedCollection 的长度大约是列表的 7 倍,但仅比 Dictionary 对象长约 50%。考虑到 KeyedCollection 是这两者的结合,Add 的性能是完全合理的,它运行的重复键检查显然不会花费太多时间。您可能想在 KeyedCollection 上运行类似的测试,如果它的速度明显变慢,您可以开始寻找其他地方(检查您的MyObject.Keygetter 以确保您没有从中获得开销)。


旧回应

你有没有尝试过:

this.kc = that.kc.MemberwiseClone() as MyKeyedCollection;

有关 MemberwiseClone 的更多信息在这里

于 2009-06-11T22:56:07.860 回答
3

好的,有一点不安全代码的解决方案怎么样?只是为了好玩?

警告!这是为 windows 操作系统和 32 位编码的,但没有理由不能修改此技术以适用于 64 位或其他操作系统。最后,我在 3.5 框架上对此进行了测试。我认为它适用于 2.0 和 3.0,但我没有测试。如果 Redmond 在修订版或补丁之间更改实例变量的数量、类型或顺序,那么这将不起作用。

但这太快了!!!

这会侵入 KeyedCollection、其底层 List<> 和 Dictionary<> 并复制所有内部数据和属性。这是一个 hack,因为要做到这一点,您必须访问私有内部变量。我基本上为 KeyedCollection、List 和 Dictionary 制作了一些结构,它们是这些类的私有变量,顺序正确。我只是将这些结构指向类所在的位置,瞧……您可以弄乱私有变量!我使用 RedGate 反射器查看所有代码在做什么,以便找出要复制的内容。然后它只是复制一些值类型并在几个地方使用 Array.Copy 的问题。

结果是CopyKeyedCollection <,>、CopyDict <> 和CopyList <>。您将获得一个可以快速复制 Dictionary<> 的功能和一个可以免费快速复制 List<> 的功能!

在完成这一切时我注意到的一件事是 KeyedCollection 包含一个列表和一个字典,它们都指向相同的数据!起初我认为这很浪费,但评论者指出 KeyedCollection 专门用于同时需要有序列表和字典的情况。

无论如何,我是一个汇编/c程序员,被迫使用vb一段时间,所以我不怕做这样的黑客。我是 C# 的新手,所以请告诉我我是否违反了任何规则,或者您是否认为这很酷。

顺便说一句,我研究了垃圾收集,这应该与 GC 一起工作得很好。我认为如果我添加一些代码来为我们花费复制的 ms 修复一些内存,那将是谨慎的。你们告诉我。如果有人要求,我会添加一些评论。

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Reflection;

namespace CopyCollection {

  class CFoo {
    public int Key;
    public string Name;
  }

  class MyKeyedCollection : KeyedCollection<int, CFoo> {
    public MyKeyedCollection() : base(null, 10) { }
    protected override int GetKeyForItem(CFoo foo) {
      return foo.Key;
    }
  }

  class MyObject {
    public MyKeyedCollection kc;

    // Copy constructor
    public MyObject(MyObject that) {
      this.kc = new MyKeyedCollection();
      if (that != null) {
        CollectionTools.CopyKeyedCollection<int, CFoo>(that.kc, this.kc);
      }
    }
  }

  class Program {

    static void Main(string[] args) {

      MyObject mobj1 = new MyObject(null);
      for (int i = 0; i < 7; ++i)
        mobj1.kc.Add(new CFoo() { Key = i, Name = i.ToString() });
      // Copy mobj1
      MyObject mobj2 = new MyObject(mobj1);
      // add a bunch more items to mobj2
      for (int i = 8; i < 712324; ++i)
        mobj2.kc.Add(new CFoo() { Key = i, Name = i.ToString() });
      // copy mobj2
      MyObject mobj3 = new MyObject(mobj2);
      // put a breakpoint after here, and look at mobj's and see that it worked!
      // you can delete stuff out of mobj1 or mobj2 and see the items still in mobj3,
    }
  }

  public static class CollectionTools {

    public unsafe static KeyedCollection<TKey, TValue> CopyKeyedCollection<TKey, TValue>(
     KeyedCollection<TKey, TValue> src, 
     KeyedCollection<TKey, TValue> dst) {

      object osrc = src;
      // pointer to a structure that is a template for the instance variables 
      // of KeyedCollection<TKey, TValue>
      TKeyedCollection* psrc = (TKeyedCollection*)(*((int*)&psrc + 1));  
      object odst = dst;
      TKeyedCollection* pdst = (TKeyedCollection*)(*((int*)&pdst + 1));
      object srcObj = null;
      object dstObj = null;
      int* i = (int*)&i;  // helps me find the stack

      i[2] = (int)psrc->_01_items;
      dstObj = CopyList<TValue>(srcObj as List<TValue>);
      pdst->_01_items = (uint)i[1];

      // there is no dictionary if the # items < threshold
      if (psrc->_04_dict != 0) {
        i[2] = (int)psrc->_04_dict;
        dstObj = CopyDict<TKey, TValue>(srcObj as Dictionary<TKey, TValue>);
        pdst->_04_dict = (uint)i[1];
      }

      pdst->_03_comparer = psrc->_03_comparer;
      pdst->_05_keyCount = psrc->_05_keyCount;
      pdst->_06_threshold = psrc->_06_threshold;
      return dst;
    }

    public unsafe static List<TValue> CopyList<TValue>(
     List<TValue> src) {

      object osrc = src;
      // pointer to a structure that is a template for 
      // the instance variables of List<>
      TList* psrc = (TList*)(*((int*)&psrc + 1));  
      object srcArray = null;
      object dstArray = null;
      int* i = (int*)&i;  // helps me find things on stack

      i[2] = (int)psrc->_01_items;
      int capacity = (srcArray as Array).Length;
      List<TValue> dst = new List<TValue>(capacity);
      TList* pdst = (TList*)(*((int*)&pdst + 1));
      i[1] = (int)pdst->_01_items;
      Array.Copy(srcArray as Array, dstArray as Array, capacity);

      pdst->_03_size = psrc->_03_size;

      return dst;
    }

    public unsafe static Dictionary<TKey, TValue> CopyDict<TKey, TValue>(
     Dictionary<TKey, TValue> src) {

      object osrc = src;
      // pointer to a structure that is a template for the instance 
      // variables of Dictionary<TKey, TValue>
      TDictionary* psrc = (TDictionary*)(*((int*)&psrc + 1)); 
      object srcArray = null;
      object dstArray = null;
      int* i = (int*)&i;  // helps me find the stack

      i[2] = (int)psrc->_01_buckets;
      int capacity = (srcArray as Array).Length;
      Dictionary<TKey, TValue> dst = new Dictionary<TKey, TValue>(capacity);
      TDictionary* pdst = (TDictionary*)(*((int*)&pdst + 1));
      i[1] = (int)pdst->_01_buckets;
      Array.Copy(srcArray as Array, dstArray as Array, capacity);

      i[2] = (int)psrc->_02_entries;
      i[1] = (int)pdst->_02_entries;
      Array.Copy(srcArray as Array, dstArray as Array, capacity);

      pdst->_03_comparer = psrc->_03_comparer;
      pdst->_04_m_siInfo = psrc->_04_m_siInfo;
      pdst->_08_count = psrc->_08_count;
      pdst->_10_freeList = psrc->_10_freeList;
      pdst->_11_freeCount = psrc->_11_freeCount;

      return dst;
    }

    // these are the structs that map to the private variables in the classes
    // i use uint for classes, since they are just pointers
    // statics and constants are not in the instance data.
    // I used the memory dump of visual studio to get these mapped right.
    // everything with a * I copy.  I Used RedGate reflector to look through all
    // the code to decide what needed to be copied.
    struct TKeyedCollection {
      public uint _00_MethodInfo;                  // pointer to cool type info
      // Collection
      public uint _01_items;                       // * IList<T>
      public uint _02_syncRoot;                    //   object
      // KeyedCollection
      public uint _03_comparer;                    //   IEqualityComparer<TKey> 
      public uint _04_dict;                        // * Dictionary<TKey, TItem> 
      public int _05_keyCount;                     // *
      public int _06_threshold;                    // *
      // const int defaultThreshold = 0;
    }

    struct TList {
      public uint _00_MethodInfo;                   //
      public uint _01_items;                        // * T[] 
      public uint _02_syncRoot;                     //   object
      public int _03_size;                          // *
      public int _04_version;                       //
    }

    struct TDictionary {
      // Fields
      public uint _00_MethodInfo;                   //
      public uint _01_buckets;                     // * int[] 
      public uint _02_entries;                     // * Entry<TKey, TValue>[] 
      public uint _03_comparer;                    //   IEqualityComparer<TKey> 
      public uint _04_m_siInfo;                    //   SerializationInfo
      public uint _05__syncRoot;                   //   object 
      public uint _06_keys;                        //   KeyCollection<TKey, TValue> 
      public uint _07_values;                      //   ValueCollection<TKey, TValue> 
      public int _08_count;                        // *
      public int _09_version;
      public int _10_freeList;                     // * 
      public int _11_freeCount;                    // *
    }

  }


}
于 2009-06-13T00:49:48.530 回答
0

您可以尝试序列化该对象,然后将其反序列化为一个新对象 - 我不知道这是否会获得任何性能,但它可能会。

于 2009-06-11T22:55:29.873 回答
0

如果你经常这样做,它建议你应该使用不可变集合。

这些是您不直接修改的结构,而是“修改”返回一个新对象,该对象可能使用旧对象状态但反映您所做的更改。

.Net 可以使用各种基于不可变字典/集合/树的映射(f# 中有很多,但是因为它更适合这种开发风格)

Eric Lippert 有一些关于这方面的优秀文章, AVL应该接近你想要的。

于 2009-06-12T16:20:23.047 回答
0
      /// 
      /// Clones Any Object.
      /// </summary>
      /// <param name="objectToClone">The object to clone.</param>
      /// <return>The Clone</returns>
      public static T Clone<T>(T objectToClone)
      {
         T cloned_obj = default(T);
         if ((!Object.ReferenceEquals(objectToClone, null)) && (typeof(T).IsSerializable))
         {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bin_formatter = null;
            Byte[] obj_bytes = null;

            using (MemoryStream memory_stream = new MemoryStream(1000))
            {
               bin_formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
               try
               {
                  bin_formatter.Serialize(memory_stream, objectToClone);
               }
               catch (SerializationException) { }
               obj_bytes = memory_stream.ToArray();
            }

            using (MemoryStream memory_stream = new MemoryStream(obj_bytes))
            {
               try
               {
                  cloned_obj = (T)bin_formatter.Deserialize(memory_stream);
               }
               catch (SerializationException) { }
            }
         }
         return cloned_obj;
      }

注意:objectToClone 必须是可序列化的,否则会遇到异常并返回 null。
您还需要创建自己的 IDataObject,因为 DataObject 不可序列化:


   [Serializable]
   public class MyDataObject : IDataObject
   {
      public int mData;

      public MyDataObject(int data)
      {
         mData = data;
      }

      #region IDataObject Members

      public object GetData(Type format)
      {
         return mData;
      }

      

      #endregion
   }
于 2009-06-18T15:45:25.550 回答