Skip to content

Instantly share code, notes, and snippets.

@mohamed-ali
Last active December 27, 2015 07:49
Show Gist options
  • Save mohamed-ali/7292037 to your computer and use it in GitHub Desktop.
Save mohamed-ali/7292037 to your computer and use it in GitHub Desktop.
LinkedList vs ArrayList: add to beginning of list benchmark
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Benchmark {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
LinkedList<Integer> linkedList = new LinkedList<Integer>();
Timing("ArrayList", arrayList);
Timing("LinkedList", linkedList);
}
//if I want to pass the lists to a method : this is one typical use for the typical interface
private static void Timing(String type, List<Integer> list){
//populating the list
for(int i = 0; i< 1E4; i++ ){
//the add method is implemented
//by the linkedList and the arrayList
list.add(i);
}
long start = System.currentTimeMillis();
//operations to time
//add items to the beginning if the list
for(int i = 0; i< 1E5; i++ ){
list.add(0,i);
}
long end = System.currentTimeMillis();
System.out.println("time taken :" + (end - start) + " ms for "+ type);
}
}
/*
* result:
*time taken :4783 ms for ArrayList
*time taken :18 ms for LinkedList
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment