简体   繁体   中英

Should I make one Map object and reference it all over the place or instantiate each time I need it?

I have a JavaFX controller that calls a method from many different methods within the class.

sendToNode(String name, Map<String, Object> p){}

right now in each method I will create a new map and fill it with parameters.

public void someMethod(){
    Map<String, Object> p = new HashMap();
    p.put("a", 777);
    sendToNode("slave", p);
}

Is it better (memory and efficiency wise) to create a class variable and just clear it each time instead of instantiating a new one in every method?

public MyClass{
    Map<String, Object> p = new HashMap();

    public void someMethod(){
        p.clear();
        p.put("a", 777);
        sendToNode("slave", p);
    }

}

Creating each time is inherently better; the performance hit is so minimal that you honestly shouldn't care (you probably have better places to optimize).

Moreover, by making a single class variable and clearing it out like that, you're going to introduce concurrency issues you'll just have to solve later that will be much more complicated and likely remove any performance gains you see.

Premature optimization is the root of all evil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM