Deleting items from an Array List from the end has a time complexity of O(1), just like deleting items from the head of a Linked List. But Linked List is still a bit faster when I test it in java and I don't quit understand why. Can somebody explain why is Linked List still faster even though they're both in O(1) time complexity?
I don't think that my code will help you answer my question, since it is more about Data Structure. But here it is just in case (don't mind the French it's for a homework) :
LinkedList<Integer> LinkL = new LinkedList<Integer>();
ArrayList<Integer> ArrL = new ArrayList<Integer>();
int N;
N = 1000;
//2.creer le Linked List
for(int i=0; i<N; i++) {
LinkL.add(i);
}
//System.out.println(LinkL);
//3. et 4.Supprimer les elements de Linked List et afficher le temps
long debut = System.nanoTime();
for(int i=0; i<N; i++) {
LinkL.removeFirst();
}
long fin = System.nanoTime();
long tempsExecution = fin - debut;
System.out.println("1.Suppression des éléments de LinkL avec la méthode \nremoveFirst( ) de LinkedList, avec une durée \nduréeLinkedList = "+tempsExecution+ " nanosecondes"); //-
//5.Creer Array List
for(int i=0; i<N; i++) {
ArrL.add(i);
}
//System.out.println(ArrL);
//6.Supprimer les elements de Array List et afficher le temps
debut = System.nanoTime();
for(int i=0; i<N; i++) {
ArrL.remove(0);
}
fin = System.nanoTime();
tempsExecution = fin - debut;
System.out.println("\n2.Suppression des éléments de ArrL avec remove(0) d’un \nArrayList, durée duréeArrayDirect = "+tempsExecution+ " nanosecondes");
//7. Recreer ArrL
for(int i=0; i<N; i++) {
ArrL.add(i);
}
//System.out.println(ArrL);
//Supprimer les elements de ArrL
debut = System.nanoTime();
for(int i=N-1; i>=0; i--) {
ArrL.remove(i);
}
fin = System.nanoTime();
tempsExecution = fin - debut;
System.out.println("\n3.Suppression des éléments de ArrL avec remove(i) ciblant \nles derniers éléments d’un ArrayList, avec une durée \nde duréeArrayInverse = "+tempsExecution+ " nanosecondes");
}
}
Thanks in advance.