Reputation: 39
Which is more efficient, faster and why? Accessing the objects in the array directly or creating a temp object?
For android system i was told that direct access is better, faster and less garbage collection
public static Foo [10][10];
public class Foo{
int score;
int age;
int type;
}
Option One:
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;
}
Option Two:
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;
}
Thank you
Upvotes: 1
Views: 43
Reputation: 6527
The best method is 2nd one and you can made a modification as follows,
public class Foo{
private int score;
private int age;
private int type;
// getters and setters for the variables
}
And do as,
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();
}
}
Upvotes: 1
Reputation: 5639
Option 2 will be faster cause the VM needs only one array lookup for your Foo
Object, that means the array bounds have only be to checked once not 3 times.
Anyway, you can also use a foreach-loop, which is faster to read by others maybe by the VM too:
for(Foo[] row: rows)
for(Foo foo: row){
int temp = foo.score;
int temp_two = foo.age;
int temp_three = foo.type;
}
Upvotes: 1