Martin11175
Martin11175

Reputation: 117

What is the performance impact of having a return type over a void?

I'm currently digging my way through some very old code in order to extend it and I keep coming across methods that could quite easily return void. The most infamous one in my mind going along the lines of:

public int dbInsert(int userID)
{
    Map<String, Integer> foo = new HashMap<String, Integer>();
    foo.put("bar", 0);
    foo.put("user", userID);

    sqlInsert(foo);
    return foo.get("bar") != null ? (Integer) foo.get("bar") : 0;
}

I think there's a big re-do coming up anyway, but I was just wondering how much of an impact stripping out method like this to a void return type (as the code snippet above always returns 0) would affect performance or whether the compiler would recognise the indifference and ignore it?

Upvotes: 1

Views: 1422

Answers (2)

Bruce Lucas
Bruce Lucas

Reputation: 959

Generally the compiler won't be able to eliminate the returned value because it doesn't know who is going to be using the method. As for the performance, your best bet is to code up a sample and measure it yourself by calling it in a loop enough times to get a run time of several seconds at least. Answers to a performance questions based on anything other than measurement are just educated guesses.

Upvotes: 3

It's negligible. Your method signature should be determined based on what makes sense from an API-use perspective.

Upvotes: 6

Related Questions