Tom Tucker
Tom Tucker

Reputation: 11906

Overhead in creating an empty array?

In order convert a List to an array, you need an empty array like following:

List<Foo> fooList;
Foo[] foos = fooList.toArray(new Foo[0]);

I happen to use this code snippet a lot, so instead of creating an empty array every time, I decided to create a static empty array, and use it each time. e.g.

private static Foo[] EMPTY_FOOS = new Foo[0];

List<Foo> fooList;
Foo[] foos = fooList.toArray(EMPTY_FOOS);

Is this worth it or are we looking at a difference of 0.000000000000000000000000000000000000000000000000000001ms?

Upvotes: 1

Views: 522

Answers (3)

Kevin Hooke
Kevin Hooke

Reputation: 2621

I think it would make more sense to question why you need to convert arrays to Lists and vice versa in the first place. You'll be better off sticking with the Collection classes if you can and avoiding the use of arrays as they are more error prone that using Collection classes.

If you use that snippet of code 'a lot' then write a method that you can reuse, but in order to determine what effort you should invest in optimizing this code, you need to profile it and see what the overhead is in relation to your other code and how often this code is actually used at runtime.

As Knuth said: "premature optimization is the root of all evil" :-)

Upvotes: 1

Alex D
Alex D

Reputation: 30445

On my computer, creating 100,000,000 Object[0] arrays takes 2.9 seconds. If you are creating a million arrays per second, or even 100,000, it might make a measurable difference.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Actually I believe this is the best performing version:

fooList.toArray(new Foo[fooList.size()]);

This way toArray() always has the exact array and no extra arrays are created. IntelliJ suggests such a refactoring out of the box.

Upvotes: 7

Related Questions