++ x比Java中的x ++更有效吗? [英] Is ++x more efficient than x++ in Java?

查看:102
本文介绍了++ x比Java中的x ++更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编程课程中,教授教我们 x ++ ++ x ,x是一个整数。

During a programming class, the professor was teaching us about x++ and ++x, with x being an integer.

他说,在这种情况下,我们可以只放 x ++ ++ x ++ x 效率更高(但从理论上讲,效率仍然更高)。

He said that in the scenario we are able to just put either x++ or ++x, ++x is more efficient (by little, but still, in theory, more efficient nonetheless).

但我忘了为什么。有谁知道?这与Java有关。

But I forgot why. Anyone knows? This was with Java.

推荐答案

在Java中效率不高。在递增/递减运算符可能过载的语言中它可以更有效,但是性能完全相同。

It's not more efficient in Java. It can be more efficient in languages where the increment/decrement operators can be overloaded, but otherwise the performance is exactly the same.

之间的差异x ++ ++ x x ++ 返回 x 增加之前, ++ x 返回 x 之后的值它增加了。在代码生成方面,两者都弥补了完全相同数量的指令,至少当你可以互换使用时(如果你不能互换使用它们,你不应该担心哪一个更快,你应该是选择你需要的那个)。唯一的区别是放置增量指令的位置。

The difference between x++ and ++x is that x++ returns the value of x before it was incremented, and ++x returns the value of x after it was incremented. In terms of code generation, both make up for the exact same number of instructions, at least when you can use either interchangeably (if you can't use them interchangeably, you shouldn't be worrying about which one is faster, you should be picking the one you need). The only difference is where the increment instruction is placed.

在C ++中,类可以重载两个前缀( ++ x )和后缀( x ++ )运算符。当处理重载它们的类型时,使用前缀运算符几乎普遍更快,因为后缀运算符的语义将返回对象的副本,就像它在增量之前一样,即使你不使用它,前缀运算符可以简单地返回对修改对象的引用(并且上帝知道C ++开发人员更喜欢返回引用而不是副本)。这个可以是一个考虑 ++ x 优于 x ++ 的理由:如果你获益习惯使用 ++ x 当你/切换到C ++时,你可以省去一些轻微的性能问题。但是在Java的上下文中,两者都是绝对等价的。

In C++, classes can overload both the prefix (++x) and postfix (x++) operators. When dealing with types that overload them, it is almost universally faster to use the prefix operator because the semantics of the postfix operator will return a copy of the object as it was before the increment, even when you wouldn't use it, while the prefix operator can simply return a reference to the modified object (and God knows C++ developers prefer to return references rather than copies). This could be a reason to consider ++x superior to x++: if you gain the habit of using ++x you could save yourself some slight performance trouble when/if you switch to C++. But in the context of Java only, both are absolutely equivalent.

与上面的注释中的 pst 非常相似,我从不使用返回值 x ++ ++ x ,如果你从未这样做过,你应该坚持使用你喜欢的那个。

Much like pst in the comments above, I never use the return value of x++ or ++x, and if you never do either, you should probably just stick to the one you prefer.

这篇关于++ x比Java中的x ++更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆