So a common programming practice for when an array can't hold the amount of information we want it to, is to double the size of an array. We do this by creating a new array, with double the original arrays size, populating this new array with the old values, and setting it as the old array. Here's a example in Java:
public int[] doubleArray(int[] old) {
int[] doubled = new int[old.length * 2];
for (int i = 0; i < old.length; i++) {
doubled[i] = old[i];
}
return doubled;
}
So is it more better to use a standard array and double the size, when needed, or to simply use an ArrayList (which changes its own size based on the input you give it by 1)? Basically, is it better to double an arrays size when you need to store more than the array allows, or to increase its size by 1 each time? And what would be the limit to which one becomes a better choice than the other?
If I had to guess, using a standard array should be faster, given that it's in the java.lang
, so I made the following class to test my theory:
public class ArrayTesting {
public static void main(String[] args) {
long startTime1 = System.nanoTime();
int[] ints = new int[10];
for (int i = 0; i < ints.length; i++) {
ints[i] = i * 2;
}
long timeToSetOriginalValues = (System.nanoTime() - startTime1);
long startTime2 = System.nanoTime();
ints = doubleArray(ints);
long timeToDouble = (System.nanoTime() - startTime2);
long startTime3 = System.nanoTime();
for (int i = 9; i < ints.length; i++) {
ints[i] = i * 2;
}
long timeToSetNewValues = (System.nanoTime() - startTime3);
System.out.println("Set Values in " + timeToSetOriginalValues);
System.out.println("Doubled Array in " + timeToDouble);
System.out.println("Finished setting values in " + timeToSetNewValues);
System.out.println("Total time: " + (timeToSetOriginalValues + timeToDouble + timeToSetNewValues));
}
public static int[] doubleArray(int[] old) {
int[] doubled = new int[old.length * 2];
for (int i = 0; i < old.length; i++) {
doubled[i] = old[i];
}
return doubled;
}
}
But for an unknown reason, I am getting extremely varying results. Varying total time from everything between 11,000 and 4,000. Assuming it's something I did wrong, is there someone better at timing who could answer my question?