Search code examples
javaperformancecoding-style

Initializing Objects to null or new?


I'm developing a web app and a question arose when I receive parameters on server-side. I initialize my DTO's (Data Transfer Object) as local variables to null and when a specific parameter is passed, I initialize my object to new. An example to illustrate my code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Object_DTO object_DTO = null;

    if(request.getParameter("parameter").equals("hello")) {
        object_DTO = new Object_DTO();
        object_DTO.setAttr("attr");
        ...
    }
}

My question regarding performance is: what's the best way to initialize objects? Should I set it to new on declaration or keep the manner I'm doing?


Solution

  • I personally believe it depends on scope. Is object_DTO used outside that if statement? In this code example, it might be useful to use null.

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Note that unless except in certain cases (IoC)
        // this scenario is quite easy to avoid
        Object_DTO object_DTO = null;
    
        if(request.getParameter("parameter").equals("hello")) {
            object_DTO = new Object_DTO();
            object_DTO.setAttr("attr");
            ...
        } else if (request.getParameter("parameter").equals("goodbye")) {
            object_DTO = new Object_DTO();
        }
    
        if (object_DTO == null) {
            // Bad response
        }
    }
    

    Otherwise, always try to use the most limited scope for a variable, but performance-wise this is minor.

    On a seperate performance note, however, I would stop calling getParameter() repeatedly. Assign it to a String and refer to that instead:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String parameter = request.getParameter("parameter");
    
        if (parameter.equals("hello")) {
            Object_DTO = new Object_DTO();
            ...
        }
    }