One important optimization is to pre-allocate the number of elements in "someOtherArray", because otherwise it will do a lot of redistribution - of course, depending on the number of elements you are dealing with. Since we donβt know the resulting size in advance, the easiest way is to set the capacity of someOtherArray to foos size using
someOtherArray.ensureCapacity(foos.size());
Of course, this does not make sense if the foos is huge and only a few elements are usually labeled.
Also note that your method should probably clear () someOtherArray first.
Another optimization I can think of is access to foos elements. You can try using a typical for (int i = 0; i < size; i++) loop for (int i = 0; i < size; i++) and initialize fooObject with foos.get(i) . This method is likely to be faster if "advanced for" is implemented by obtaining a copy of the elements in the array or, possibly, when receiving an iterator. But I think the iteration over ArrayList gets special optimization in the compiler ... Maybe others have experience in this area.
source share