Vos secondes options sont nettement plus efficaces puisque vous ne faites qu'une recherche par rapport à n nombre de fois dans la première option.
Mais, rien ne vaut mieux que de l'essayer quand vous le pouvez.Voici donc ce qu'il -
(Pas assez parfait, mais bon de vérifier les hypothèses et sur ma machine de toute façon)
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
// populate map
int mapSize = 500000;
int strLength = 5;
for(int i=0;i<mapSize;i++)
map.put(RandomStringUtils.random(strLength), RandomUtils.nextInt());
long start = System.currentTimeMillis();
// alt. #1
for (String key : map.keySet()) {
Integer value = map.get(key);
// use key and value
}
System.out.println("Alt #1 took "+(System.currentTimeMillis()-start)+" ms");
start = System.currentTimeMillis();
// alt. #2
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// use key and value
}
System.out.println("Alt #2 took "+(System.currentTimeMillis()-start)+" ms");
}
RÉSULTATS (Des quelques intéressants)
Avec int mapSize = 5000; int strLength = 5;
Alt # 1 a pris 26 ms
L'Alt n ° 2 a pris 20 ms
Avec int mapSize = 50000; int strLength = 5;
Alt # 1 a 32 ms
Alt # 2 a pris 20 ms
Avec int mapSize = 50000; int strLength = 50;
Alt # 1 a eu 22 ms
Alt # 2 a 21 ms
Avec int mapSize = 50000; int strLength = 500;
Alt # 1 a pris 28 ms
Alt # 2 a 23 ms
Avec int mapSize = 500000; int strLength = 5;
Alt # 1 a pris 92 ms
Alt # 2 a 57 ms
... et ainsi de suite
Juste quelle est la carte? Cela sent l'optimisation prématurée. –
@Matt Je demande parce que j'ai plusieurs d'entre eux, et ils sont énormes - généralement à hauteur de 10K-100K éléments; il y a certainement un bon cas d'optimisation! – bguiz
Mise à jour: Beaucoup de réponses semblent penser qu'il s'agit d'une optimisation prématurée. Notez que ce qui précède est en effet un SSCCE (http://sscce.org/), et non le bit de code que je cherche à optimiser! – bguiz