Skip to content

Instantly share code, notes, and snippets.

@thescouser89
Created November 27, 2014 02:52
Show Gist options
  • Save thescouser89/e5b74cd798655279b756 to your computer and use it in GitHub Desktop.
Save thescouser89/e5b74cd798655279b756 to your computer and use it in GitHub Desktop.
Micro Benchmarks for HashMap vs Array
import java.util.*;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ConcurrentHashMap<Integer, Long> map;
long[] array_key;
long[] array_value;
long avgHashMapTime;
long avgArrayTime;
map = new ConcurrentHashMap<Integer, Long>();
long start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
map.put(i, 1234L);
}
long end = System.nanoTime();
avgHashMapTime = end - start;
array_key = new long[1_000_000];
array_value = new long[1_000_000];
long start_array = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
array_key[i] = i;
array_value[i] = i;
}
long end_array = System.nanoTime();
avgArrayTime = end_array - start_array;
System.out.format("HashMap Insert time:\t %20d\n", avgHashMapTime);
System.out.format("Array Insert time:\t %20d\n", avgArrayTime);
start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
long x = map.get(i);
}
end = System.nanoTime();
System.out.format("HashMap Get time:\t %20d\n", end - start);
start_array = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
long x = array_value[i];
long y = array_key[i];
}
end_array = System.nanoTime();
System.out.format("Array Get time:\t \t %20d\n", end_array - start_array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment