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 がこれら 2 つの組み合わせであることを考えると、Add のパフォーマンスは完全に合理的であり、Add が実行する重複キー チェックにそれほど時間がかからないことは明らかです。KeyedCollection で同様のテストを実行することをお勧めします。大幅に遅くなる場合は、別の場所を探し始めることができます ( MyObject.Keygetter をチェックして、オーバーヘッドが発生していないことを確認してください)。


古い応答

やってみました:

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

MemberwiseClone の詳細については、こちらをご覧ください。

于 2009-06-11T22:56:07.860 に答える
3

わかりました、安全でないコードを少し使ったソリューションはいかがですか? ただの楽しみ?

警告!これは Windows OS および 32 ビット用にコーディングされていますが、この手法を変更して 64 ビットまたはその他の OS で動作しない理由はありません。最後に、これを 3.5 フレームワークでテストしました。2.0 と 3.0 で動作すると思いますが、テストはしていません。レドモンドがリビジョンまたはパッチ間でインスタンス変数の数、タイプ、または順序を変更した場合、これは機能しません。

しかし、これは速いです!!!

これは、KeyedCollection、その基になる List<> および Dictionary<> にハッキングし、すべての内部データとプロパティをコピーします。これを行うには、プライベート内部変数にアクセスする必要があるため、ハックです。基本的に、これらのクラスのプライベート変数である KeyedCollection、List、および Dictionary の構造を正しい順序で作成しました。これらの構造体をクラスの場所に向けるだけで、出来上がり...プライベート変数をいじることができます!! RedGate リフレクターを使用して、すべてのコードが何を行っているかを確認し、何をコピーするかを判断しました。次に、いくつかの値の型をコピーし、いくつかの場所で Array.Copy を使用するだけです。

結果は、 CopyKeyedCollection <,>、CopyDict <>、およびCopyList <> です。Dictionary<> をすばやくコピーできる関数と、List<> をすばやくコピーできる関数を無料で入手できます。

これをすべて実行して気づいたことの 1 つは、KeyedCollection にはリストとディクショナリがすべて同じデータを指しているということです。最初はこれは無駄だと思っていましたが、コメンテーターは、KeyedCollection は順序付きリストと辞書が同時に必要な場合に特に適していると指摘しました。

とにかく、私はしばらくの間 vb を使用することを余儀なくされたアセンブリ/C プログラマーなので、このようなハックを行うことを恐れていません。私は C# を初めて使用するので、ルールに違反したかどうか、またはこれがクールだと思うかどうか教えてください。

ちなみに、ガベージ コレクションについて調べたところ、これは GC で問題なく動作するはずです。少しコードを追加して、コピーに費やすミリ秒のメモリを修正するのが賢明だと思います。教えてください。リクエストがあればコメントを追加します。

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
      /// 
      /// 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 は Serializable である必要があります。そうしないと、例外が発生し、null が返されます。
また、DataObject は Serializable ではないため、独自の IDataObject を作成する必要があります。


   [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 に答える
0

これを頻繁に行う場合は、代わりに不変のコレクションを使用する必要があることを示唆しています。

これらは、直接変更しない構造ですが、代わりに「変更」により、古いオブジェクトの状態を使用する可能性のある新しいオブジェクトが返されますが、行った変更が反映されます。

さまざまな不変の辞書/セット/ツリー ベースのマップを .Net で使用できます (多くは f# ですが、このスタイルの開発により適しているため)。

Eric Lippert はこれに関するいくつかの優れた記事を書いており、AVL ツリーはまさにあなたが望むものに近いはずです。

于 2009-06-12T16:20:23.047 に答える
0

オブジェクトをシリアライズしてから、デシリアライズして新しいオブジェクトにすることもできます。パフォーマンスが向上するかどうかはわかりませんが、可能性はあります。

于 2009-06-11T22:55:29.873 に答える