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?
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.
The first case is clearly the one which would do more work. There are at least two possibilities:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With