Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

why so big garbage cause in dictionary?

Discussion in 'Scripting' started by dreamerflyer, Sep 30, 2016.

  1. dreamerflyer

    dreamerflyer

    Joined:
    Jun 11, 2011
    Posts:
    927
    gc1.jpg gc2.png
    Code (CSharp):
    1.         collider_MatchingDataDic = new Dictionary<Collider ,CombinedChildMatchinData> (1000);
    2.         for (int i = 0; i < CombineMeshInstanceDic_keys.Length; i++)
    3.         {
    4.             CombineMeshInstanceDic.Add (CombineMeshInstanceDic_keys [i], CombineMeshInstanceDic_values [i].instantList);
    5.             //init collider
    6.             for (int j = 0; j < CombineMeshInstanceDic_values [i].instantList.Count; j++)
    7.             {
    8.                 collider_MatchingDataDic.Add (CombineMeshInstanceDic_values [i].instantList [j].scriptData.matchCollider, CombineMeshInstanceDic_values [i].instantList [j].scriptData);
    9.             }
    10.         }
    when set ollider_MatchingDataDic size =1000 will cause more gargage!
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    4,744
    Yeah, the dictionary's data needs to be stored somewhere! The Dictionary has some kind of collection structure (probably an array, idk) on the back end, so there's memory cost to creating the dictionray. When you're asking it to have a size of 1000, it'll pre-allocate a backing of at least 1000 elements.

    If you're doing this a bunch, reuse the dictionary by clearing it. If you're just using it from Start, it won't matter.
     
  3. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    557
    Is your CombinedChildMatchinData a struct ? In which case what you see is heavy duty boxing.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    4,744
    Does Dictionary.Add cause a boxing?
     
  5. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    557
    @Baste Interesting, did a quick search and you're right it avoids boxing by using that array internally !

    ps: OP like baste said there's no allocation involved past initialization if you re-use an existing dictionary of proper size by clearing it (and regardless of using struct of class, sorry for my confusion earlier).
     
    Last edited: Sep 30, 2016
unityunity