1

In Java, for ages, when you wanted to convert a Collection into an array you did this: coll.toArray(new ItemObject[coll.size()]). However, in Android Studio I got a warning. Here's the full text of the warning's explanation as provided by Android Studio:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

But this explanation is only considering HotSpot, the Java VM, so I wonder: Is this warning also valid for Android? Are those improvements mentioned above also implemented? What would be the fastest way of converting a collection to an array on Android?

EDIT: I know it doesn't matter a lot nowadays, still I'd like to know. =)

niqueco
  • 2,261
  • 19
  • 39
  • I don't think you should worry that much about arrays performance (at least until you have millions of object to allocate). So just stick with whatever style you like the most – Karma Maker Oct 08 '18 at 20:53
  • Use the new String[0] option. It tells you why the other is a bad idea for concurrency reasons. And unless the operation is called very frequently, the speed difference will never matter. – Gabe Sechan Oct 08 '18 at 20:55
  • @KarmaMaker I know, you are right! Still, I'd like to know. =) – niqueco Oct 08 '18 at 21:05
  • There is a [related question for modern (non Android) JVMs](https://stackoverflow.com/questions/174093/toarraynew-myclass0-or-toarraynew-myclassmylist-size). – Raedwald Nov 13 '18 at 11:00

0 Answers0