Reputation: 1763
I am generating many ModelAndView objects in my controller (one per web page I send) but I don't know which strategy will save more memory and will be better in performance.
These are my two options:
1- Keep an attribute in my Controller and reuse it every time:
@Controller
public class MyController{
private ModelAndView mav;
public ModelAndView methodA() {
mav = new ModelAndView(...);
return mav;
}
public ModelAndView methodB() {
mav = new ModelAndView(...);
return mav;
}
...
}
2- Create one object foreach method:
@Controller
public class MyController{
public ModelAndView methodA() {
ModelAndView mav = new ModelAndView(...);
return mav;
}
public ModelAndView methodB() {
ModelAndView mav = new ModelAndView(...);
return mav;
}
...
}
It is any important improvement in one of them? Thank you
Upvotes: 2
Views: 2354
Reputation: 2687
I think that singleton pattern is what you are looking for :-)
good explanation with example here : http://www.oodesign.com/singleton-pattern.html
Upvotes: 0
Reputation:
If the object is not supposed to change state, meaning that you wish to maintain it then you can use a singleton and stop creating new instances each time.
Upvotes: 0
Reputation: 6522
Definitely avoid #1 for concurrency reasons. You could have thread A running method 1 and thread B running method 2, and one of the will change the mav object before the other one can use the one it constructed.
Upvotes: 3