Question

I wrote the following code in my application. ( office work )

@Override
public List<Outlet> getAllOutletForTouch() {
    return outletDao.getOutlets();
}

This is the code one of my colleagues wrote.

@Override
public List<Outlet> getAllOutletsForMobile() {
    List<Outlet> outletList = outletDao.getOutlets();
    return outletList;
}

He created a new variable, assigned the values, and then returned the values; whereas I just returned the values directly calling the method. What is the convention for doing this?

Was it helpful?

Solution

As such there is no considerable performance difference in 2nd option as compare to the 1st, even on large scale, since as soon as the reference goes out of scope it will be GCed.

But it mostly about the coding style. IMO and as @Luiggi said in comments, 1st option is more readable but doesn't allow you to debug on return. If the return statement can throw exception that you might wanna debug, you need to go with 2nd option.

OTHER TIPS

I would prefer first one in your case. You are unecessarily creating a new reference in 2nd case which goes to thread stack occupying some memory. So i would go with first.

EDIT:

Elaborating my answer based on comments. An object is created on heap but all the references to that object go to Thread Stack.

So if multiple threads refer to same object then they will store their own reference in their stack.

EDIT:

Check the link Where is allocated variable reference, in stack or in the heap? for details of how references are stored

I think the first one (returning directly without creating variable) is better because we should always avoid creating variables if they are not useful.

There is not much performance hit but still make it a practice not to create useless variables.

Someone said that it will be GCed as soon as it goes out of scope but according to my understanding there is no fixed time when GC runs and you cannot force it to run. So it will stay in memory till the next time GC runs.

There's no performance penalty for #2. If it's executed frequent enough, VM will take care of optimizing it.

The #2 style is redundant and unnecessary, but no big deal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top