开发者

toArray(new MyObject[size]) vs iterating over list and filling the array

开发者 https://www.devze.com 2023-02-23 00:43 出处:网络
which one of the following methodologies is safe from performance hits, assume that the size of List is large (may be 1,000 objects).

which one of the following methodologies is safe from performance hits, assume that the size of List is large (may be 1,000 objects).

i)

List<String> myList = new ArrayList<String>();

for(int i=0; i <=10; i++){
    myList.add(""+i);
}

String[] array = myList开发者_高级运维.toArray(new String[myList.size()]);

myArrayMethod(array); // this method returns the array - it modifies the content but not size of array.

myListMethod(myList); // this method processes the list.

ii)

List<String> myList = new ArrayList<String>();

for(int i=0; i <=10; i++){
    myList.add(""+i);
}

String[] array = new String[myList.size()];
int i = 0;
for(String str : myList){
   array[i] = myList.get(i);
   i++;
}
myArrayMethod(array); // this method returns the array - it modifies the content but not size of array.

myListMethod(myList); // this method processes the list.


The first example is slightly more efficient as it can use System.arraycopy() internally.

However, compared to everything else you are doing e.g. creating the Strings, it makes a very little difference and I would suggest you do what you believe is clearer


toArray() is much readable and faster.

If you look at source code toArray method you'll notice that there are some conditionals and arraycopy method.

// ArrayList.class:
public <T> T[] toArray(T[] a) {
    if (a.length < size) 
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

// System.class
public static native void arraycopy // native method

The arraycopy is much faster for huge array than manually adding. I've tested it, I checked duration for i) and for ii)

  • i) your first example: toArray
  • ii) your second: manual adding

100 000 elements: i) 2 ms ii) 12 ms

1 000 000 elements: i) 10 ms ii) 65 ms


I would go with option 1 if it were my code, because I just have a feeling the Collections API will do this better than I will.


Relatively speaking they have the same performance characteristics, so given that, use the built in version

String[] array = myList.toArray(new String[myList.size()]);
0

精彩评论

暂无评论...
验证码 换一张
取 消