Java中的原始数据类型和可移植性

前端之家收集整理的这篇文章主要介绍了Java中的原始数据类型和可移植性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我引用Herbert Schildt的第3章数据类型,变量和数组:

The primitive types represent single values not complex objects.
Although Java is otherwise completely object-oriented,the primitive
types are not. The reason for this efficiency. Making the primitive
types would have degraded performance too much.

The primitive types are defined to have an explicit range and
mathematical behavior. Languages such as C,C++ allow the size of an
integer to vary based upon the dictates of the execution environment.
However,Java is different. Because of Java’s portability requirement,
all data types have a strongly defined range. For example,an int is
always 32-bit regardless of the particular platform. This allows
programs to be written that are guaranteed to run without porting on
any machine architecture. While strictly specifying the size of an
integer may cause a small loss of performance in some environments,it
is necessary in order to achieve portability.

他最后两行是什么意思?如何指定整数的大小可能会导致某些环境中的性能损失很小?

解决方法

在“较低”语言中,原始数据类型大小通常来自cpu处理它们的能力.
例如,在 c中,int被定义为“大小至少为16位”,但其大小可能因架构而异,以确保“int类型应该是目标处理器最有效的整数类型”. “. ( source).这意味着如果您的代码对int的大小做了粗心的假设,如果将它从32位 x86移植到64位 powerpc,它可能会破坏.

如上所述,java是不同的. int,例如,总是32位.这意味着当您在不同的体系结构上运行相同的代码时,您不必担心其大小更改.如上所述,权衡是性能 – 在任何本身不处理32位计算的体系结构中,这些整数需要扩展到cpu可以处理的本机大小(这将有一个小的惩罚),或者更糟,如果cpu只能处理较小的int,则int上的每个操作都可能需要多次cpu操作.

原文链接:https://www.f2er.com/java/127352.html

猜你在找的Java相关文章