2014-10-18 59 views
1

哪種效率更高,速度更快?爲什麼? 直接訪問數組中的對象或創建臨時對象?訪問2個Diminsional陣列的對象

對於Android系統我被告知,直接訪問是更好,更快,更小的垃圾收集

public static Foo [10][10]; 

    public class Foo{ 
    int score; 
    int age; 
    int type; 
    } 

方案一:

for(int col = 0; col < 10; col++) 
    for(int row = 0; row < 10; row++){ 
    int temp = Foo[col][row].score; 
    int temp_two = Foo[col][row].age; 
    int temp_three = Foo[col][row].type; 

    } 

方案二:

for(int col = 0; col < 10; col++) 
    for(int row = 0; row < 10; row++){ 
     Foo tempFoo = Foo[col][row]; 

     int temp = tempFoo.score; 
     int temp_two = tempFoo.age; 
     int temp_three = tempFoo.type; 

    } 

謝謝

回答

1

選項2將更快,因此VM只需要對您的Foo對象進行一個陣列查找,這意味着數組邊界僅需要檢查一次而不是3次。

無論如何,你也可以使用一個foreach循環,這是更快被別人讀取可能由VM太:

for(Foo[] row: rows) 
    for(Foo foo: row){ 
     int temp = foo.score; 
     int temp_two = foo.age; 
     int temp_three = foo.type; 
    } 
+0

克里斯 - 嗨,如果我改變任何由臨時FOO訪問的變量會導致變化在原始的foo中存儲在數組中? (foo.score = 5) – 2014-10-18 19:51:34

+0

是的,因爲temp foo是對原始foo的引用。它不是副本。 – trooper 2014-10-18 19:55:56

1

最好的方法是:第二個,你可以按照如下進行了修改,

public class Foo{ 
    private int score; 
    private int age; 
    private int type; 

    // getters and setters for the variables 
} 

而且做的,

for(int col = 0; col < 10; col++){ 
    for(int row = 0; row < 10; row++){ 
     Foo tempFoo = Foo[col][row]; 
     int temp  = tempFoo.getScore(); 
     int temp_two = tempFoo.getAge(); 
     int temp_three = tempFoo.getType(); 
    } 
}