考虑以下代码:
Foo result = array[index];
index = (index + 1) % array.length;
return result;
为了执行一些最终操作,需要额外的变量。这样写是否有意义:
try {
return array[index];
} finally {
index = (index + 1) % array.length;
}
或者会对性能产生影响吗?一般来说,这被认为是一种好/坏的做法,如果是这样,为什么?
(在示例中,假设 index
是 array
的有效索引,并且代码不会抛出 ArrayIndexOutOfBoundsException
)
编辑:问题不在于是否需要使用 try-finally
,而在于我选择这样做所获得的性能增益或损失。没有它,就会创建一个变量。有了它,返回的值可能会以更有效的方式存储在其他地方。
最佳答案
正如评论所述,主要开销是使用 %
而不是条件或掩码
您可以使用 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)];
}
我的机器上的结果...您的里程将会有所不同
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
越高越好。
简而言之,使用 finally
可能会稍微慢一些,但与其他替代方案相比,我不会担心它。
关于java - 使用try-finally执行return后的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139479/