后增量和前增量运算符之间的性能差异? [英] Performance difference between post- and pre- increment operators?
问题描述
在Java中,使用后增量与前增量运算符会对性能产生影响吗? (在其他语言中,在某些情况下,预增量可能比后增量快.)
In Java, would there be any performance impact in using post increment vs pre increment operator? (In other languages, a pre-increment can be faster than a post-increment in certain contexts.)
例如,这些循环在性能上有区别吗?
For example, is there a performance difference in these loops?
for (int n = 0; idx < max; ++idx) { /* Note pre-increment */
f(max);
}
VS.
for (int n = 0; idx < max; idx++) { /* Note post-increment */
f(max);
}
推荐答案
只有在功能行为相同的情况下,性能问题才有意义(因为如果功能不同,则正确的行为要优于每分钟-更快),所以我假设您所指的是不使用表达式值的情况?也就是说,表达式的唯一目的是增加i
吗?在这种情况下,答案是否定的:没有性能差异,实际上没有任何差异.我刚刚编译了此类:
A performance question only makes sense in a context where the functional behavior is identical (since, if the functionality is different, a correct behavior is superior to a minutely-faster one), so I'm assuming that you're referring to a situation where the value of the expression is not used? That is, where the only purpose of the expression is to increment i
? In such a situation, the answer is no: no performance difference, and in fact, no difference whatsoever. I just compiled this class:
public class Foo
{
public static void main(final String args[])
{
int i = Integer.parseInt(args[0]);
i++;
}
}
并计算所得Foo.class
的MD5校验和;并且,对于带有++i
的版本也是如此.它们具有相同的校验和,表明这两个版本被编译为 exact 相同的字节码,因此它们在 literally 上的执行方式相同.
and computed the MD5 checksum of the resulting Foo.class
; and, similarly for a version with ++i
instead. They had the same checksum, indicating that the two versions were compiled into the exact same bytecode, and would therefore perform literally identically.
(自然,从理论上讲,这可能取决于编译器.即使在等效的情况下,其他编译器也可能会决定不同于++i
来编译i++
,但是我对此表示怀疑,它是真的,即使是这样也不值得担心.)
(Naturally, this could, in theory, depend on the compiler. A different compiler might decide to compile i++
differently from ++i
even in a context where they're equivalent. But I doubt that, and it's really not worth worrying about even if it the case.)
这篇关于后增量和前增量运算符之间的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!