为什么在计算表达式时将字节和短值提升为int [英] Why byte and short values are promoted to int when an expression is evaluated

查看:87
本文介绍了为什么在计算表达式时将字节和短值提升为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么每次对表达式求值或按位运算时将byteshort值提升为int的原因吗?

解决方案

因为Java语言规范是这样说的. 第5.6.1节定义了一元数值提升以用于某些运算符的撤消,它说:

  • 如果操作数的编译时类型为byte,short或char,则通过扩展原语转换(第5.1.2节)将其提升为int类型的值.

第5.6.2节在评估二进制数值运算符("binary"表示具有两个操作数,例如"+"的运算符)时表示类似的内容:

  • 如果其中一个操作数的类型为double,则另一个将转换为double.
  • 否则,如果其中一个操作数的类型为float,则另一个将转换为float.
  • 否则,如果其中一个操作数的类型为long,则另一个将转换为long.
  • 否则,两个操作数都将转换为int类型.

为什么用这种方式定义?主要原因是在设计Java语言和Java虚拟机时,计算机的标准字长为32位,而使用较小类型的基本算术在性能上没有优势.通过将32位用作int大小,然后在 解决方案

Because the Java Language Specification says so. Section 5.6.1 defines unary numeric promotion for evaulation of certain operators, and it says:

  • If the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

Section 5.6.2 on evaluation of binary numeric operators ('binary' meaning operators that have two operands, like '+') says something similar:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Why was it defined this way? A major reason is that at the time of design of the Java language and Java virtual machine, 32-bit was the standard word size of computers, where there is no performance advantage to doing basic arithmetic with smaller types. The Java virtual machine was designed to take advantage of this, by using 32-bit as the int size, and then providing dedicated instructions in the Java bytecode for arithmetic with ints, longs, floats, and doubles, but not with any of the smaller numeric types (byte, short, and char). Eliminating the smaller types makes the bytecode simpler, and lets the complete instruction set, with room for future expansion, still fit the opcode in a single byte. Similarly, the JVM was designed with a bias towards easy implementation on 32-bit systems, in the layout of data in classes and in the stack, where 64-bit types (doubles and longs) take two slots and all other types (32-bit or smaller) take one slot.

So, the smaller types were generally treated as second-class citizens in the design of Java, converted to ints at various steps, because that simplified some things. The smaller types are still important because they take less memory when packed together (e.g., in arrays), but they do not help when evaluating expressions.

这篇关于为什么在计算表达式时将字节和短值提升为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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