.toArray(new MyClass [0])或.toArray(new MyClass [myList.size()])? [英] .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

查看:92
本文介绍了.toArray(new MyClass [0])或.toArray(new MyClass [myList.size()])?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个ArrayList

Assuming I have an ArrayList

ArrayList<MyClass> myList;

我想调用toArray,是否有性能原因要使用

And I want to call toArray, is there a performance reason to use

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);

MyClass[] arr = myList.toArray(new MyClass[0]);

,因为它更少的冗长,我认为编译器将确保空数组不真正创建,但我一直在想,如果这是真的。

I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.

当然,在99%的情况下,它没有区别单向或其他,但我想保持一个一致的风格,我的正常代码和我优化的内部循环...

Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...

推荐答案

截至 Java 5中的ArrayList ,如果数组具有正确的大小(或更大),则数组将被填充。因此

As of ArrayList in Java 5, the array will be filled already if it has the right size (or is bigger). Consequently

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);

将创建一个数组对象,填充它并将其返回到arr。另一方面

will create one array object, fill it and return it to "arr". On the other hand

MyClass[] arr = myList.toArray(new MyClass[0]);

将创建两个数组。第二个是长度为0的MyClass数组。因此,对象的对象创建将立即被抛弃。至于源代码建议编译器/ JIT不能优化这一个,使它不被创建。此外,使用零长度对象会导致toArray()方法中的转换。

will create two arrays. The second one is an array of MyClass with length 0. So there is an object creation for an object that will be thrown away immediately. As far as the source code suggests the compiler / JIT cannot optimize this one so that it is not created. Additionally, using the zero-length object results in casting(s) within the toArray() - method.

查看ArrayList.toArray()的源代码:

See the source of ArrayList.toArray():

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

使用第一个方法,以便只创建一个对象,但是昂贵)铸件。

Use the first method so that only one object is created and avoid (implicit but nevertheless expensive) castings.

这篇关于.toArray(new MyClass [0])或.toArray(new MyClass [myList.size()])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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