There are many ways to skin a cat, but only six ways to process an ArrayList. Thus, let's test the performance of each method. Run it on your system and let us know about your results. Please, give a basic system info if you post. Thanks!
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListSpeedTest {
public static void main(String[] args) {
long time=System.currentTimeMillis();
ArrayList<String> colors=new ArrayList<>();
for(int i=0;i<100000;i++){ //create a bunch of items for the list, change the value if needed
colors.add("Red"+i);
}
System.out.printf("Initializing ArrayList time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
for(int i=0;i<colors.size();i++);
//System.out.println(colors.get(i)+" ");
System.out.printf("Simple for loop: %32s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
for(String color:colors);
//System.out.println(color+" ");
System.out.printf("Enhanced for loop time: %25s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
int i=0;
while(i++<colors.size());
//System.out.println(colors.get(i++)+" ");
System.out.printf("While loop time: %32s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
//Iterator - hasNext, next, remove
Iterator<String> iterator = colors.iterator();
while(iterator.hasNext())iterator.next();
//System.out.println(iterator.next()+" ");
System.out.printf("While loop Iterator time: %23s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
//ListIterator - hasNext, next, remove, hasPrevious, previous, add
ListIterator<String> lIterator = colors.listIterator();
while(lIterator.hasNext())lIterator.next();
//System.out.println(lIterator.next()+" ");
System.out.printf("While loop ListIterator time: %19s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
//Java 8 Stream
colors.forEach((color)->{});
//System.out.println(color+" ");});
System.out.printf("ForEach Stream time: %28s\n",(getTime(System.currentTimeMillis()-time)));
time=System.currentTimeMillis();
String name="\n6 Ways to process an ArrayList and speed performance test by Zoltan Szabo";
name.toUpperCase().chars().forEach(s->{
System.out.print((char)s);
});
}
private static String getTime(long millis){
long second = (millis / 1000) % 60;
long minute = (millis / (1000 * 60)) % 60;
long hour = (millis / (1000 * 60 * 60)) % 24;
return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
}
}
No comments:
Post a Comment