Created
August 5, 2012 23:52
-
-
Save aadnk/3268133 to your computer and use it in GitHub Desktop.
Benchmark for list range removal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class ListRangeTests { | |
public final static int COUNT = 100000; | |
public final static int REPEAT = 20; | |
public static void main(String[] args) { | |
// Test all methods | |
for (int i = 0; i < 3; i++) { | |
long time = 0; | |
for (int j = 0; j < REPEAT; j++) { | |
List<Integer> source = constructList(COUNT); | |
long start = System.nanoTime(); | |
testMethod(source, i); | |
time += System.nanoTime() - start; | |
} | |
System.out | |
.println("Method # " + i + ": " + (getMilli(time) / (double)REPEAT) + " ms"); | |
} | |
} | |
private static void testMethod(List<Integer> source, int alternative) { | |
switch (alternative) { | |
case 0: | |
// Slow method! | |
int length = source.size() / 2; | |
int index = source.size() / 2 - 1; | |
for (int i = 0; i < length; i++) | |
source.remove(index); | |
break; | |
case 1: | |
int toIndex = source.size() / 2 - 1; | |
// Alternative one | |
for (int i = source.size() - 1; i > toIndex; i--) | |
source.remove(i); | |
break; | |
case 2: | |
// Alternative two | |
source.subList(source.size() / 2, source.size()).clear(); | |
break; | |
default: | |
throw new IllegalArgumentException("Not an algorithm: " + alternative); | |
} | |
// Sanity test | |
if (source.size() != COUNT / 2) | |
throw new IllegalStateException("Algorithm failed to divide the list."); | |
} | |
private static double getMilli(long time) { | |
return time / 1000000.0; | |
} | |
private static List<Integer> constructList(int count) { | |
List<Integer> source = new ArrayList<Integer>(); | |
// Add 100 000 consecutive integers | |
for (int i = 0; i < count; i++) { | |
source.add(i); | |
} | |
return source; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment