Skip to content

Conversation

@ArthurGazizov
Copy link

@ArthurGazizov ArthurGazizov commented Apr 4, 2021

Description

empty-array is recommended in modern java

Object[] objArray = collection.toArray(new Object[0]);

Reference

  • intellij insepction

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).

Researches

https://shipilev.net/blog/2016/arrays-wisdom-ancients/#_new_reflective_array
https://code.i-harness.com/en/q/2a80d

@philsttr philsttr merged commit d20c337 into logfellow:master Apr 19, 2021
@philsttr philsttr added this to the 7.0 milestone Apr 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants