List.toArray(Object[]) performance [duplicate]
Asked Answered
P

2

9

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 ?

Phionna answered 7/4, 2014 at 12:57 Comment(3)
Why not transform and collect into an array in one step? You are not forced to use CollectionUtils. Even better, just use Java 8.Hosiery
I can't use Java 8 at the moment, although I'd like to know the name of feature that Java 8 offers for this. I can loop and transform the objects but less code is better. So if toArray doesn't cause a big performance hit, I may use it.Phionna
i dont think there is big difference, when you have a look at code CollectionUtils.collect it is looping through list and transforming object, which is your first two steps from your alternative methodColvin
T
5

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.

Tagalog answered 7/4, 2014 at 13:7 Comment(3)
What do you mean by linear ?Phionna
What I mean is that performance(time) is proportional to input size because it is based on a single loop.Tagalog
@MuhammadGelbana as opposed to quadratic etc. linear basically means no nested loops.Amosamount
S
3

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.

Schiedam answered 19/2, 2016 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.