Search code examples
javaperformancetry-finally

Using try-finally to execute statements after return


Consider the following code:

Foo result = array[index];
index = (index + 1) % array.length;
return result;

In order to perform some final actions an extra variable is required. Does it make sense to write it as:

try {
    return array[index];
} finally {
    index = (index + 1) % array.length;
}

or will it have an impact on performance? It is, in general, considered a good/bad practice, and if so, why?

(In the example it is assumed that index is a valid index for array and the code will not throw an ArrayIndexOutOfBoundsException)

Edit: the question is not about the need to use try-finally but rather about any gain or loss in performance I get by choosing to do it. Without it, a variable is created. With it, the returned value is stored somewhere else, perhaps in a more efficient way.


Solution

  • Without the finally you declare indeed an additional Foo variable.
    But is it really expensive ? Not as in both cases the Foo object exists in memory. You just added a reference to access to it.
    A reference to an object in the scope of a method is really cheap.
    You should never worry about that.

    Besides, you don't have to use finally statement as a way to improve the performance of the executed code.
    Readers of the code will never guess such a thing.
    finally serves to :

    The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

    and

    putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

    The first code without the finally statement is much clearer and doesn't have any reading indirection.

    So I advise to stick to :

    Foo result = array[index];
    index = (index + 1) % array.length;
    return result;