Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there performance implications when using ArrayList.get() many times per iteration?

For Android development in general, is it more expensive to do the following: (Example 1)

for(int x=0; x < largeObjectCollection.size(); x++){
    largeObjectCollection.get(x).SomeValueOne   = "Sample Value 1";
    largeObjectCollection.get(x).SomeValueTwo   = "Sample Value 2";
    largeObjectCollection.get(x).SomeValueThree = "Sample Value 3" ;
    //Continues on to over 30 properties...
}

Over this implementation (Example 2)

for(int x=0; x < largeObjectCollection.size(); x++){
   SampleObjectIns myObject = largeObjectCollection.get(x);
   myObject.SomeValueOne   = "Sample Value 1";
   myObject.SomeValueTwo   = "Sample Value 2";
   myObject.SomeValueThree = "Sample Value 3" ;
   //Continues on to over 30 properties...
}

I couldn't find any break down of performance implications when using .get() multiple times instead of creating a new instance of that object each iteration.

I'm thinking that .get() doesn't use much in terms of resources since the position of the element is already known, but when dealing with many properties is it best to just fetch that object once as shown in example two?

like image 372
Dayan Avatar asked Feb 24 '17 14:02

Dayan


2 Answers

There is no performance impact of calling get() method several times in a looping construct.

The get() method doesn't do any searching kind of stuff. The position is known, hence the exact location in the RAM is also known. So all it needs to do it make a single RAM access which is a constant time operation - O(1).

So, you can use it multiple times without any performance impact. But a much cleaner approach would be to use get() once, store it in a local variable and them re-use that variable.

like image 102
Aritra Roy Avatar answered Oct 13 '22 01:10

Aritra Roy


The first case is clearly the one which would do more work. There are at least two possibilities:

  • The JIT might be able to determine that the list values aren't changing, and that you're requesting the same value repeatedly; and thus it effectively converts it into the second form.
  • The ArrayList.get operation is just really fast; it's basically just doing an array lookup, and the value it looks up is in cache already because you've just looked it up.

    So, your timing measurement is dominated by the other work that you're doing. So, even if you're doing 29 more get calls than necessary, 30 times a tiny number is still a tiny number.

like image 33
Andy Turner Avatar answered Oct 13 '22 02:10

Andy Turner