Java: Performance Implications of Inline Initialization Of HashMaps
This question already has an answer here:
@davison this question has been discussed many times on SO. Even if the data structure is not the same (Set, HashSet) instead of (Map, HashMap) I personally think the following is the best discussion and should clarify all your doubts: Efficiency of Java "Double Brace Initialization"?
This is not a good practise, because it creates a new anonymous inner class which the JVM has to use more memory to keep track of. Other than that, it's mostly harmless.
A better way of writing this code would be to use an initialisation block:
Map<String, String> aMap = new HashMap<String, String>();
{
aMap.put("gloves", "hand");
aMap.put("hat", "head");
aMap.put("shoes", "feet");
aMap.put("scarf", "neck");
}
What are the performance implication of using the above code to initialize hashmaps inline?
Almost none. The first time you do it there is extra class loading which is unlikely to be important unless you care about the number of classes you use.
I have not seen this being used very often. Is it considered to be a good java practice ?
I would say it is good practice if it makes the code clearer, esp in unit tests.
Where it is bad practice is if this collection gets put in a thread local as this can prevent the module unloading.
链接地址: http://www.djcxy.com/p/82390.html上一篇: java中的双Brace初始化