++运算符比a = a + 1更有效吗?

编程入门 行业动态 更新时间:2024-10-19 17:33:22
本文介绍了++运算符比a = a + 1更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Java中,增量运算符是否比简单的加法运算更有效?

In Java, Is the increment operator more efficient that a simple addition operation?

推荐答案

它编译为完全相同的字节代码。这都是首选问题。

编辑:事实证明这是 NOT true。

EDIT:As it turns out this is NOT true.

public class SO_Test { public static void main(String[] args) { int a = 1; a++; a += 1; ++a; } }

输出:

示例:

public class SO_Test { public static void main(String[] args) { int a = 1; a = a + 1; a++; a += 1; ++a; } }

输出:

可以在 Java字节码指令列表页面。简而言之, a = a + 1 发出 iload_1 , iconst_1 , iadd 和 istore_1 ,而其他人只使用 iinc 。

The differences can be analyzed on the Java bytecode instruction listings page. In short, a = a + 1 issues iload_1, iconst_1, iadd and istore_1, whereas the others only use iinc.

来自@NPE:

流行的理念是javac故意选择不是优化生成的代码,依靠JIT编译器在运行时执行此操作。后者有更好的关于执行环境(硬件架构等)的信息,以及代码如何在运行时使用。

The prevailing philosophy is that javac deliberately chooses not to optimize generated code, relying on the JIT compiler to do that at runtime. The latter has far better information about the execution environment (hardware architecture etc) as well as how the code is being used at runtime.

总而言之,除了不编译相同的字节代码,概率非常高,它也不会有所作为。这只是一种风格选择。

So in conclusion, besides not compiling to the same byte code, with exceedingly high probability, it won't make a difference. It's just a stylistic choice.

更多推荐

++运算符比a = a + 1更有效吗?

本文发布于:2023-11-25 22:53:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更有效   运算符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!