Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.toArray(Object[]) performance [duplicate]

I'm getting a List of object A, then I use Apache Commons Collection4 to transform the obtained List from having A instances to having B instances.

    listOfBs = (List<B>) CollectionUtils.collect(listOfAs, componentTransformer);

However, eventually I need to have an Array of Bs not a List.

So my question is, which is faster.

  1. Convert the list using CollectionUtils.collect
  2. Create an array using listOfBs.toArray(new B[listOfBs.size()])

Or

  1. Loop over the listOfAs
  2. Transform each A object to a B object
  3. Add each B object to an array (B[])

The difference between the first approach and the second approach is that the first approach has much less code, but I'm not sure if the toArray method bares a hidden loop or expensive operations.

What I see in the second approach is that I'm sure I'll loop only once over the listOfAs list.

So which approach is faster ?

like image 315
Muhammad Gelbana Avatar asked Apr 07 '14 12:04

Muhammad Gelbana


2 Answers

Don't be concerned about performance of List.toArray(), its complexity is linear as it will resort to a single loop internally.

As it is implemented with Arrays.copyOf, which eventually comes to System.arraycopy, that is implemented in native code it could be potentially even faster than a java-level loop.

like image 181
kiruwka Avatar answered Sep 19 '22 01:09

kiruwka


Very interesting to read is this article:http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion

It goes into great detail about the different ways to convert a List to an array.

Conclusion: do not use listOfBs.toArray(new B[listOfBs.size()]) as stated by you, but use listOfBs.toArray(new B[0]).

Believe it or not, this is faster.

like image 36
rmuller Avatar answered Sep 21 '22 01:09

rmuller