2016-12-03 49 views
0

假設您在對象中有10個索引引用(#0至9)。然而,其中2個在我們班的特定實例中未被使用(例如,#3和#8)。 這裏是我的問題: 內存和性能方面,最好的選擇是什麼:長度爲10的索引數組,索引爲3和8的空值,或者大小爲8的列表以及指向該列表中的引用索引?對象列表vs列表+索引數組

溶液1將看起來像這樣:

class SomeObject{ 
    OtherObject[] references = new OtherObject[10]; 
    { 
     for(int i = 0; i<10; i++){ 
      if(i != 3 && i != 8) 
       references[0] = new OtherObject(); 
      //otherwise just keep the null value 
     } 
    } 

    //then to use (here getting the toString() value) 
    String getStringOfObjectAtIndex(int index){ 
     //in real code we'd first check that index is within 0-9 
     if(references[index] != null) 
      return references[index].toString(); 
     else 
      return "";//no reference for that index 
    } 
} 

雖然溶液2會更喜歡這樣:

class SomeObject{ 
    ArrayList<OtherObject> references = new ArrayList<>(0); 
    int[] pointers = new int[10]; 
    { 
     for(int i = 0; i<10; i++){ 
      if(i != 3 && i != 8){ 
       pointers[i] = references.size(); 
       references.add(new OtherObject()); 
      }else{ 
       pointers[i] = -1;//no reference available 
      } 
     } 
    } 

    //then to use (here getting the toString() value) 
    String getStringOfObjectAtIndex(int index){ 
     //in real code we'd first check that index is within 0-9 
     if(pointers[index] != -1) 
      return references.get(pointers[index]).toString(); 
     else 
      return "";//no reference for that index 
    } 
} 

TL; DR:比一個較大的陣列內的空引用詮釋?

回答

1

在第一種情況下,假設引用的開銷爲64位,則需要128位來存儲兩個空引用,並且代碼易於理解和維護。

在第二種情況下,您需要額外的10個整數(即10 * 32位,加上陣列本身至少16個字節),並且代碼是卷積的。更不用說ArrayList本身與數組相比有額外的開銷,並且無論如何將包含大於8的數組來保存元素。

無論如何,這看起來很像過早優化,這是所有邪惡的根源。使用最簡單,最明顯,最易讀和可維護的解決方案。它有足夠快的速度,甚至有機會成爲記憶中最快和最低的。

如果您有一個非常大且非常稀疏的數組,可以使用其他策略。但在這種情況下,使用Map<Integer, OtherObject>會更簡單。