Skip to content

Instantly share code, notes, and snippets.

@julianhyde
Created November 21, 2013 18:23
Show Gist options
  • Save julianhyde/7586790 to your computer and use it in GitHub Desktop.
Save julianhyde/7586790 to your computer and use it in GitHub Desktop.
Benchmark that measures alternative implementations of a map with case-insensitive string keys. The first implementation is a hash-map whose keys are converted to upper-case. The second implementation is a list whose entries are compared using String.equalsIgnoreCase. The two interesting variables are n (the number of elements in the collection)…
/**
* Benchmark that measures alternative implementations of a map with case-insensitive
* string keys. The first implementation is a hash-map whose keys are converted to
* upper-case. The second implementation is a list whose entries are compared using
* String.equalsIgnoreCase.
*
* <p>The two interesting variables are n (the number of elements in the collection)
* and name(int x) (the function that generates the list of entries).
*
* <p>We access each element of the collection once, because that will be typical for
* my motivating use case, ResultSet.getString(String).
*
* <p>List seems to be the faster implementation up to about n = 35.
*/
public class CaseInsensitiveMapVersusListBenchmark {
public static void main(String[] args) {
final HashMap<String, Integer> map = new HashMap<String, Integer>();
final List<String> list = new ArrayList<String>();
int n = 40;
for (int i = 0; i < n; i++) {
String s = name(i);
map.put(s.toUpperCase(), i);
list.add(s);
}
for (int z = 0; z < 3; z++) {
long t0 = System.nanoTime();
int k = xxxx(map, n);
System.out.println("map: " + (System.nanoTime() - t0) + " : " + k);
t0 = System.nanoTime();
xxxx(list, n);
System.out.println("list: " + (System.nanoTime() - t0) + " : " + k);
}
}
static String name(int i) {
return "xxxxxxx" + i;
}
static int xxxx(List<String> list, int n) {
int x = 0;
for (int i = 0; i < n; i++) {
final String s = name(i);
x += anInt(list, s);
}
return x;
}
static int anInt(List<String> list, String s) {
final int size = list.size();
for (int i = 0; i < size; i++) {
String s1 = list.get(i);
if (s1.equalsIgnoreCase(s)) {
return i;
}
}
return -1;
}
static int xxxx(HashMap<String, Integer> map, int n) {
int x = 0;
for (int i = 0; i < n; i++) {
x += map.get((name(i)).toUpperCase());
}
return x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment