toArray with pre sized array toArray with pre sized array android android

toArray with pre sized array


Great question.

https://shipilev.net/blog/2016/arrays-wisdom-ancients/#_new_reflective_array

Bottom line: toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now. Future VM optimizations may close this performance gap for toArray(new T[size]), rendering the current "believed to be optimal" usages on par with an actually optimal one. Further improvements in toArray APIs would follow the same logic as toArray(new T[0]) — the collection itself should create the appropriate storage.


It reads since late updates of OpenJDK 6 and it does not matter which run-time is being used to run it - because the language-level of the code, which runs as compiled classes on Dalvik, might be Java 6, 7, 8. it only matters which language-level the project used to compile it. For example:

compileOptions {    sourceCompatibility JavaVersion.VERSION_1_8    targetCompatibility JavaVersion.VERSION_1_8}

Setting JavaVersion.VERSION_1_6 might possibly even disable the inspection complaint... fixing performance issues on these dated devices is probably not worth the effort - and some/most might not even be affected, because only the "earlier updates" behave different than all what followed up.


I am not a Java historian, but...

HotSpot appears to be essentially a brand name for a particular kind of JVM maintained and distributed by Oracle. It takes its name from the just-in-time compiler that can detect "hot spots" of frequently-executed code and optimize them on the fly.

The Android Runtime also has this JIT compiler behavior, as well as ahead-of-time compilation of java bytecode into native machine code at installation time.

This makes me think that ART falls into the same category as HotSpot (as far as this inspection is concerned), and therefore that you should use the "empty array" version of this call.


When in doubt, measure!

The best way to know for sure is to write a test program that executes both versions of the method and measures which one runs faster.


Sources: