具有预先确定大小的数组的toArray [英] toArray with pre sized array

查看:82
本文介绍了具有预先确定大小的数组的toArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 ar.toArray(new String [ar.size()])时,Android Studio 3.2.1 警告有关预先设置大小的数组,并建议使用空数组:

when using ar.toArray(new String[ar.size()]) Android studio 3.2.1 warns about pre-sized array and recommends empty array:

有两种样式可以将集合转换为数组:预定大小的数组(例如c.toArray(new String [c.size()]))或使用空数组(如c.toArray(new String [0]).在较旧的Java版本中建议使用预先设置的数组,因为反射调用是创建适当大小的数组所必需的速度非常慢.然而自从OpenJDK 6的最新更新以来,此调用引起了人们的注意,空数组版本的性能相同,有时甚至比预大小版本更好.还通过了预尺寸数组对于并发或同步集合是危险的,因为在size和toArray调用之间可能会发生数据争用如果集合是在手术过程中同时缩小.这项检查可以遵循统一的样式:使用一个空数组(即建议在现代Java中使用)或使用预定大小的数组(可能是在较旧的Java版本或非基于HotSpot的JVM中更快.

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

是Android还是Java?

is it true for Android or just for java?

使用预定大小的数组(在较早的Java版本中可能会更快或非基于HotSpot的JVM).

using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

因为我认为Android不是HotSpot,所以其虚拟机是Dalvik,而现在是ART

because i think Android is non-HotSpot its virtual machine was Dalvik and now it is ART

推荐答案

好问题.

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

底线: toArray(new T [0])似乎更快,更安全且符合合同规定更清洁,因此现在应该是默认选择.未来虚拟机优化可能会弥补 toArray(new T [size])的性能差距,使当前的被认为是最佳的"用法与实际上是最佳选择.进一步

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.

这篇关于具有预先确定大小的数组的toArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆