Explicación diferencias entre HashMap y TreeMap
Publicado por Juan José (3 intervenciones) el 14/12/2020 13:57:49
Estoy intentando dar una explicación lógica para poder diferenciar la velocidad entre cada uno de estos mapas, tengo este código Java para ir cambiando valores y ver la velocidad de cada uno.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package org.eda1.ejercicio04;
import java.util.HashMap;
import java.util.TreeMap;
public class HashMap_vs_TreeMap {
private static int nItems = 2000000;
private static int nFinds = 5000000;
public static void pruebaHash_String() {
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
long tI;
System.out.println("**** PRUEBA CON CLAVE STRING ****");
tI = System.nanoTime();
for (int i=0; i<nItems; i++) {
treeMap.put(String.valueOf(i), i);
}
System.out.println("tPut(tree): " + (System.nanoTime()-tI)/1e6 + "ms");
tI = System.nanoTime();
for (int i=0; i<nItems; i++) {
hashMap.put(String.valueOf(i), i);
}
System.out.println("tPut(hash): " + (System.nanoTime()-tI)/1e6 + "ms");
tI = System.nanoTime();
for (int i=0; i<nFinds; i++) {
treeMap.get(String.valueOf((int)(Math.random()*nItems)));
}
System.out.println("tGet(tree): " + (System.nanoTime()-tI)/1e6 + "ms");
tI = System.nanoTime();
for (int i=0; i<nFinds; i++) {
hashMap.get(String.valueOf((int)(Math.random()*nItems)));
}
System.out.println("tGet(hash): " + (System.nanoTime()-tI)/1e6 + "ms");
}
public static void main(String[] args) {
HashMap_vs_TreeMap.pruebaHash_String();
}
}
Valora esta pregunta


0