2014-10-18 2 views
1

어떤 것이 더 효율적이고 빠르며 그 이유는 무엇입니까? 배열의 객체에 직접 액세스하거나 temp 객체를 생성 하시겠습니까? 안드로이드 시스템의 경우2 차원 배열의 객체에 액세스

는 내가 직접 액세스가 낫다는 것을 들었다, 빠르고 덜 가비지 컬렉션

public static Foo [10][10]; 

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

옵션 1 :

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; 

    } 

옵션 2 :

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는 Foo 개체에 대해 VM에 배열 조회가 하나만 필요할 때 더 빠르기 때문에 배열 경계가 3 회가 아닌 한 번만 검사되어야한다는 의미입니다. ,

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) –

+0

예, temp foo는 원래 foo에 대한 참조이므로. 복사본이 아닙니다. – trooper

1

가장 좋은 방법은 2 일이며, 다음과 같이 수정을했다 할 수 있습니다

어쨌든, 당신은 아마 너무 VM에 의해 다른 사람이 읽을 빠른 foreach는 루프를 사용할 수 있습니다

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(); 
    } 
}