Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Dynamic 3D array

Discussion in 'Scripting' started by m0dz_, May 4, 2014.

  1. m0dz_

    m0dz_

    Joined:
    May 4, 2014
    Posts:
    2
    Hello everyone! I'm trying to make a 3D infinite array in C# but couldn't find any online. So I came up with this code:
    Code (csharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class DArray
    6. {
    7.     //public ArrayList dynamicData;
    8.     public Dictionary<string, Object> dynamicData;
    9.  
    10.     public DArray ()
    11.     {
    12.         dynamicData = new Dictionary<string, Object>();
    13.         //dynamicData = new ArrayList();
    14.     }
    15.  
    16.     public void Set(int x, int y, int z, Object obj)
    17.     {
    18.         /*if(dynamicData[x] == null)
    19.             dynamicData[x] = new ArrayList();
    20.        
    21.         if(((ArrayList)dynamicData[x])[y] == null)
    22.             dynamicData[x] = new ArrayList();
    23.        
    24.         ((ArrayList)((ArrayList)dynamicData[x])[y])[z] = obj;*/
    25.  
    26.         String key = x + ":" + y + ":" + z;
    27.         dynamicData[key] = obj;
    28.     }
    29.  
    30.     public Object Get(int x, int y, int z)
    31.     {
    32.         /*if(dynamicData[x] == null)
    33.             return null;
    34.        
    35.         if(((ArrayList)dynamicData[x])[y] == null)
    36.             return null;
    37.        
    38.         return ((ArrayList)((ArrayList)dynamicData[x])[y])[z];*/
    39.  
    40.         String key = x + ":" + y + ":" + z;
    41.        
    42.         if(!dynamicData.ContainsKey(key))
    43.             return null;
    44.  
    45.         return dynamicData[key];
    46.     }
    47. }
    After switching from a non-infinite array to this one, I noticed a huge performance decrease. Is there any way to fix it?
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Performance loss possibly due to using strings as keys.
    Maybe try hashing the xyz values or something
     
  3. m0dz_

    m0dz_

    Joined:
    May 4, 2014
    Posts:
    2
    I tried to hash it like this:
    Code (csharp):
    1.  
    2.     public int GetHashCode(int x, int y, int z)
    3.     {
    4.         int hash = unchecked(x + (31 * y) + (31 * 31 * z));
    5.         return hash;
    6.     }
    7.  
    (This is for minecraft-like voxel terrain)
    But it causes some coordinates to have the same key.
     
  4. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Can you just use longs for more bits?