Let's look at the case when you have an array of 1 element and you want to increase the size to dynamically hold 1 million elements.
Case 1:
String [] wordList = new String[1]; String [] tmp = new String[wordList.length + 1]; for(int i = 0; i < wordList.length ; i++){ tmp[i] = wordList[i]; } wordList = tmp;
Case 2 (increase in size with the addition coefficient):
String [] wordList = new String[1]; String [] tmp = new String[wordList.length + 10]; for(int i = 0; i < wordList.length ; i++){ tmp[i] = wordList[i]; } wordList = tmp;
Case 3 (increase in size by multiplication factor):
String [] wordList = new String[1]; String [] tmp = new String[wordList.length * 2]; for(int i = 0; i < wordList.length ; i++){ tmp[i] = wordList[i]; } wordList = tmp;
When you increase the size of the array dynamically, using Array.copy or iterating over the array and copying the elements to the new array using the for loop, it actually iterates over each element of the array. This is an expensive operation. Array.copy will be clean and optimized, still expensive. So, I would suggest increasing the length of the array by a multiplication factor.
How does that help
In case 1, to place 1 million elements, you need to increase the size of the array 1 million - 1 times, i.e. 999,999 times.
In case 2, you need to increase the size of the array 1 million / 10 - 1 times, that is 99,999 times.
In case 3, you need to increase the size of the array by log 2 1 million - 1 times, that is, 18.9 (hypothetically).
Ashwin agggarwal
source share