Skip to content

Instantly share code, notes, and snippets.

@TrevorS
Last active December 28, 2015 08:49
Show Gist options
  • Select an option

  • Save TrevorS/7474338 to your computer and use it in GitHub Desktop.

Select an option

Save TrevorS/7474338 to your computer and use it in GitHub Desktop.
Benchmarking Sorting collections (ArrayList vs TreeSet).
package benchmarks;
import java.util.*;
public class BenchmarkSortingCollections {
private static Random random = new Random();
private static long START = 0;
private static long END = 50000000000000L;
private static int MAX_SIZE = 1000000;
public static void main(String[] args) {
System.out.println("Running Sort Test w/ ArrayList.");
long[] listResults = collectResultsList();
System.out.println("Running Sort Test w/ TreeSet.");
long[] setResults = collectResultsSet();
printResults(listResults, setResults);
}
private static long[] collectResultsList() {
long[] results = new long[MAX_SIZE];
for (int i = 0; i < MAX_SIZE; i+= 10000) {
results[i] = runSortTestWithArrayList(i);
}
return results;
}
private static long[] collectResultsSet() {
long[] results = new long[MAX_SIZE];
for (int i = 0; i < MAX_SIZE; i+= 10000) {
results[i] = runSortTestWithTreeSet(i);
}
return results;
}
private static void printResults(long[] listResults, long[] setResults) {
System.out.println("Elements, Elements in Thousands, List Duration in NS, Set Duration in NS, " +
"List Duration in MS, Set Duration in MS");
for (int i = 0; i < listResults.length; i++) {
if (listResults[i] > 0 || setResults[i] > 0) {
System.out.println(i + ", " + (i / 1000.0) + ", " + listResults[i] + ", " + setResults[i]
+ ", " + (listResults[i] / 1000000.0) + ", " + (setResults[i] / 1000000.0));
}
}
}
private static long getRandomLong() {
return START + ((long) (random.nextDouble() * (END - START)));
}
private static long runSortTestWithArrayList(long size) {
List<Long> numbers = new ArrayList<Long>();
long startTime = System.nanoTime();
for (long i = 0; i < size; i++) {
numbers.add(getRandomLong());
}
Collections.sort(numbers);
return System.nanoTime() - startTime;
}
private static long runSortTestWithTreeSet(long size) {
Set<Long> numbers = new TreeSet<Long>();
long startTime = System.nanoTime();
for (long i = 0; i < size; i++) {
numbers.add(getRandomLong());
}
return System.nanoTime() - startTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment