gpt4 book ai didi

java - 无论如何,Byte 是作为 Int 实现的吗?

转载 作者:搜寻专家 更新时间:2023-11-01 01:43:42 25 4
gpt4 key购买 nike

我有一本 java 游戏书建议尽可能将所有数据实现为 Int,该类型运行速度最快。它说 Byte、Char 和 Boolean 无论如何都是作为 Int 实现的,所以你不会节省空间,而且你最终不得不在代码中进行转换,因为 Byte 数据会减慢速度。例如,

需要强制转换

a = (字节)(b+c);

由于加法结果是一个Int,即使a,b,c都声明为Bytes。

我目前在我的游戏中有一个声明为 Byte 的巨大二维数组,以节省空间和进行按位运算。它真的节省空间吗?我还在示例中看到了对 Int 进行的按位运算,按位运算是否按预期对 Ints 进行了工作?

最佳答案

这通常是不正确的。事实上,JVM Specification §2.3 中对此进行了概述。 :

The primitive data types supported by the Java Virtual Machine are the numeric types, the boolean type (§2.3.4), and the returnAddress type (§2.3.3).

The numeric types consist of the integral types (§2.3.1) and the floating-point types (§2.3.2).

The integral types are:

  • byte, whose values are 8-bit signed two's-complement integers, and whose default value is zero

  • short, whose values are 16-bit signed two's-complement integers, and whose default value is zero

  • int, whose values are 32-bit signed two's-complement integers, and whose default value is zero

  • long, whose values are 64-bit signed two's-complement integers, and whose default value is zero

  • char, whose values are 16-bit unsigned integers representing Unicode code points in the Basic Multilingual Plane, encoded with UTF-16, and whose default value is the null code point ('\u0000')

现在,对于 boolean 来说,情况略有不同。来自 §2.3.4 :

Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. There are no Java Virtual Machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type.

根据您使用的是 byte[] 还是 int[],您可以看到字节码的差异,因此它们并不相同:

byte[] b = {42};
ICONST_1NEWARRAY T_BYTEDUPICONST_0BIPUSH 42BASTOREASTORE 1

vs

int[] b = {42};
ICONST_1NEWARRAY T_INTDUPICONST_0BIPUSH 42IASTOREASTORE 1

Is it actually saving space?

是的,很可能是这样,尤其是在数组非常大的情况下。

do bitwise operations work as expected on Ints?

是的,他们有。

关于java - 无论如何,Byte 是作为 Int 实现的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19078834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com