I am going to slightly disagree with some of the other answers, and say that ArrayList.add()
will clearly be both more memory efficient and faster.
ArrayList
will in fact create an array that is a bit bigger in size than what it needs intially, seemingly being a little less memory efficient. But it will do its best to avoid having to create many unnecessary array instances for every add operation. This is both faster and more memory efficient than your implementation.
In your implementation, for every add
, you are creating a whole new array instance. This is not memory efficient, and will add more work for the garbage collector.
EDIT:
Here is an example that illustrates what I mean by the ArrayList
being more memory efficient as well.
Let's say, we try to add 5 items to a list using both methods.
Method 1: Using built-in ArrayList
ArrayList<String> list = new ArrayList<>(); // size of internal array: 10.
list.add("a"); // size of internal array: still 10.
list.add("b"); // size of internal array: still 10.
list.add("c"); // size of internal array: still 10.
list.add("d"); // size of internal array: still 10.
list.add("e"); // size of internal array: still 10.
In total, a single array of size 10 was created.
Method 2: Custom implementation of add using normal arrays.
String[] list = new String[0]; // 1 array of size 0.
list = addItemToArray(list, "a"); // 2nd array instance of size 1.
list = addItemToArray(list, "b"); // 3rd array instance of size 2.
list = addItemToArray(list, "c"); // 4th array instance of size 3.
list = addItemToArray(list, "d"); // 5th array instance of size 4.
list = addItemToArray(list, "e"); // 6th array instance of size 5.
In total, we've created 6 arrays, of a total combined size of 15, not counting the memory overhead associated to each created object.
So, as can be seen, it doesn't take long before using the custom implementation starts costing more in memory.
That's why it's better to trust the built-in ArrayList
implementation for both memory and speed, rather than our own.
The exception to that would be if you don't plan on calling add
very often, or if you know the size that you need your array to be in advance. But even then, you can simply instantiate the ArrayList
by passing in a more specific initialCapacity
to its constructor to fit your specific needs.