Daniel H.
Daniel H.

Reputation: 432

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);
    }

}

Upvotes: 0

Views: 49

Answers (1)

whitfin
whitfin

Reputation: 4629

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.

Upvotes: 2

Related Questions