返回后使用try-finally执行语句

OLE*_*SHA 2 java performance try-finally

请考虑以下代码:

Foo result = array[index];
index = (index + 1) % array.length;
return result;
Run Code Online (Sandbox Code Playgroud)

为了执行一些最终操作,需要额外的变量.将其写为:

try {
    return array[index];
} finally {
    index = (index + 1) % array.length;
}
Run Code Online (Sandbox Code Playgroud)

还是会对绩效产生影响?一般来说,它被认为是一种好/坏的做法,如果是这样,为什么呢?

(在示例中,假设它index是一个有效的索引,array并且代码不会抛出ArrayIndexOutOfBoundsException)

编辑:问题不是关于需要使用try-finally,而是关于我选择做的任何性能上的获得或损失.没有它,就会创建一个变量.有了它,返回的值可能以更有效的方式存储在其他地方.

Pet*_*rey 5

如评论所说,主要的开销是使用%而不是条件或掩码

您可以使用JMH运行基准测试

static class Foo {

}

Foo[] array = new Foo[8];
int index = 0;

@Benchmark
public Foo simple() {
    Foo result = array[index];
    index = (index + 1) % array.length;
    return result;
}

@Benchmark
public Foo withFinally() {
    try {
        return array[index];
    } finally {
        index = (index + 1) % array.length;
    }
}

@Benchmark
public Foo withCondition() {
    int i = index++;
    if (index == array.length) index = 0;
    return array[i];
}

@Benchmark
public Foo withMask() {
    int i = index++;
    return array[i & (array.length-1)];
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上的结果......你的里程变化

Benchmark               Mode  Cnt    Score   Error   Units
ModMain.simple         thrpt   25  132.473 ± 1.764  ops/us
ModMain.withCondition  thrpt   25  363.077 ± 4.752  ops/us
ModMain.withFinally    thrpt   25  130.179 ± 1.585  ops/us
ModMain.withMask       thrpt   25  397.310 ± 3.506  ops/us
Run Code Online (Sandbox Code Playgroud)

越高越好.

简而言之,使用finally可能会稍微慢一些,但与备选方案相比,我不会担心它.