Skip to content

Instantly share code, notes, and snippets.

@kalaspuffar
Created April 6, 2018 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalaspuffar/4d6c9e484460cd5cb77aaa7814b37bdf to your computer and use it in GitHub Desktop.
Save kalaspuffar/4d6c9e484460cd5cb77aaa7814b37bdf to your computer and use it in GitHub Desktop.
Simple example of performance testing for collection types in java
package org.ea.debugger;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.function.IntConsumer;
public class CollectionTest {
public static void sleep() {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
public static long getCurrentlyUsedMemory() {
return
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() +
ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed();
}
public static String formatSize(long v) {
if (v < 1024) return v + " B";
int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
}
public static int numIterations = 100_000;
public static void runTest(IntConsumer f, String name) {
sleep();
long start = System.currentTimeMillis();
long startMem = getCurrentlyUsedMemory();
f.accept(numIterations);
System.out.println(name + ": " + (System.currentTimeMillis() - start));
System.out.println(name + "Mem: " + formatSize(getCurrentlyUsedMemory() - startMem));
}
public static void main(String[] argv) {
runTest((v) -> {
List<Integer> arrayList = new ArrayList<>();
for(int i=0; i<v; i++) {
arrayList.add(i);
}
}, "ArrayList");
runTest((v) -> {
List<Integer> linkedList = new LinkedList<>();
for(int i=0; i<v; i++) {
linkedList.add(i);
}
}, "LinkedList");
runTest((v) -> {
Map<Integer, Integer> hashMap = new HashMap<>();
for(int i=0; i<v; i++) {
hashMap.put(i, i);
}
}, "HashMap");
runTest((v) -> {
Map<Integer, Integer> treeMap = new TreeMap<>();
for(int i=0; i<v; i++) {
treeMap.put(i, i);
}
}, "TreeMap");
runTest((v) -> {
Map<Integer, Integer> linkedHashMap = new LinkedHashMap<>();
for(int i=0; i<v; i++) {
linkedHashMap.put(i, i);
}
}, "LinkedHashMap");
runTest((v) -> {
Set<Integer> hashSet = new HashSet<>();
for(int i=0; i<v; i++) {
hashSet.add(i);
}
}, "HashSet");
runTest((v) -> {
Set<Integer> linkedHashSet = new LinkedHashSet<>();
for(int i=0; i<v; i++) {
linkedHashSet.add(i);
}
}, "LinkedHashSet");
runTest((v) -> {
Set<Integer> treeSet = new TreeSet<>();
for(int i=0; i<v; i++) {
treeSet.add(i);
}
}, "TreeSet");
runTest((v) -> {
Deque<Integer> arrayDeque = new ArrayDeque<>();
for(int i=0; i<v; i++) {
arrayDeque.add(i);
}
}, "ArrayDeque");
runTest((v) -> {
Queue<Integer> priorityQueue = new PriorityQueue<>();
for(int i=0; i<v; i++) {
priorityQueue.add(i);
}
}, "PriorityQueue");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment