I am a java developer for three years but never thought about the underlying performance costs between different implementations of lists. That s why I make a benchmark like :
private static int N = 10000000;
public static void main(String args[]){
doSt(new ArrayList<String>());
doSt(new ArrayList<String>(N));
doSt(new LinkedList<String>());
}
private static List<String> doSt(List<String> fizzbuzz) {
long l = System.currentTimeMillis();
int counter = 1;
while(counter <= N){
fizzbuzz.add("aa");
counter++;
}
long l2 = System.currentTimeMillis();
System.out.println("time spent " + (l2-l));
}
and I see
time spent 148,
time spent 33,
time spent 198,
meaning that
time performance(ArrayList with initial capacity) > time performance(ArrayList) > time performance(LinkedList).
LinkedList and ArrayList is pretty close, since insertion is O(1) in both implementations, I am not bothered by the small difference.
BUT, if I change the implementation like :
private static int N = 10000000;
public static void main(String args[]){
doStWithIfElse(new ArrayList<String>());
doStWithIfElse(new ArrayList<String>(N));
doStWithIfElse(new LinkedList<String>());
}
private static List<String> doStWithIfElse(List<String> fizzbuzz) {
long l = System.currentTimeMillis();
int counter = 1;
while(counter <= N){
if (counter %3 == 0 && counter %5 == 0){
fizzbuzz.add("FizzBuzz");
}
else if (counter %3 == 0){
fizzbuzz.add("Fizz");
}
else if (counter %5 == 0){
fizzbuzz.add("Buzz");
}
else{
fizzbuzz.add(Integer.toString(counter));
} counter++;
}
long l2 = System.currentTimeMillis();
System.out.println("time spent " + (l2-l));
}
then,
time spent 516,
time spent 8452,
time spent 6808,
Then All of a sudden, ArrayList with the initial capacity becomes the poorest performer and ArrayList without the initial capacity beats them all with a big margin.
That really confused me a lot. What is the reason of performance changes when I introduce the if else statements?