Are there any performance implications when using ArrayList.get () many times to iterate?

For Android development in general, is it worth it 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... } 

In 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 could not find a single performance violation when using .get() several times instead of creating a new instance of this object at each iteration.

I think .get() does not use many resources, since the position of the element is already known, but when working with many properties, it is best to just extract this object once, as shown in Example 2

+6
source share
3 answers

The first case is obviously one that will work more. There are at least two possibilities:

  • JIT can determine that the values ​​of the list do not change and that you request the same value repeatedly; and thus he effectively transforms it into a second form.
  • The operation ArrayList.get is very fast; it basically just searches for the array, and the value it is looking for is already in the cache because you just looked at it.

    So, in your time dimension, the other work that you do dominates. That way, even if you make 29 more get calls than necessary, a 30 times tiny number is still small.

+1
source

The effect does not affect the method call to the get() method several times in the loop construct.

The get () method does not perform any search. The position is known, so the exact location in RAM is also known. Thus, all he needs to do is make one access to RAM, which is an operator with on time time - O (1) .

Thus, you can use it several times without any impact on performance. But a much simpler approach is to use get () once, store it in a local variable and reuse this variable.

+2
source

The only reason is that the get operation is really very efficient for the array, so there is practically no noticeable difference in performance.

0
source

Source: https://habr.com/ru/post/1015251/


All Articles